VS2017项目的单元测试

Unit Testing for VS2017 project

我在 VS2017 中有一个 ASP.NET 应用程序(我捕获一些输入的基本形式)。

表单中的一个字段是 Mark,它是一个整数。

我的 .cs 文件中有以下标记代码块。

    [Display(Name = "Mark")]
    [Range(1, 10, ErrorMessage = "Mark must be between 1 and 10")]                              
    public int Mark{ get; set; }

我已经为此应用程序创建了一个 MSTest 项目来编写单元测试。

我的问题是,您是否为此块编写测试用例以验证输入值是否在预期范围内?

如果是,你是怎么写的?

我已经开始了。

    [DataRow(0, "Mark must be between 1 and 10")]
    [DataRow(11, "Mark must be between 1 and 10")]
    [DataTestMethod]
    public void TestMark_IsMarkValid_NotValid(int mark, string expectedMsg)
    {
        //Arrange
        Student testStudent = new Student();
        testStudent.Mark = mark; //this does not throw any error, although the assigned value is outside of the defined range. But it looks like the range validation only applies to the webform.

        //Act

        string actualMsg = "Mark must be between 1 and 10"; //this is not correct. I was thinking to capture in the actual result the error message yield by the Range validation, but assigning a value outside range doesn't yield any error message. 

        //Assert
        Assert.AreEqual(expectedMsg, actualMsg);
    }

现在,不确定该块是否应该在单元测试范围内。如果应该的话,我感觉我采取的方法是不正确的。

有什么想法吗?

非常感谢, 科斯敏

有趣的问题。我不确定是否有绝对正确的答案。但这是我的想法:

1) "Mark" 是一个 属性。我们不需要对 属性 进行单元测试,因为 Microsoft 已经测试过该属性有效。

2) 属性不影响属性,但提供有关其他人可以使用的属性的信息。这就是您的单元测试通过该值测试的原因。表单使用属性,您的单元测试没有。这就是为什么您的单元测试可以分配任何值。

3) 如果你真的想限制变量的值,那么在 Student class 中限制它 - 通过 setter 或显式 get/set 和支持变量- 你永远不能相信浏览器提交的任何数据。

4) 测试 UI 并不容易。我们有一个手动测试的测试团队。我们尝试了几种工具,但 none 非常出色。将您的业务逻辑放在 UI 之外,并将其放在可以轻松测试的业务 class 中。

因此,为了回答您的问题,我个人不会在单元测试中测试属性功能。

希望对您有所帮助。