测试控制器方法+ DataAnnotations - asp.net mvc 3

时间:2011-06-22 14:49:45

标签: asp.net asp.net-mvc unit-testing asp.net-mvc-3

这是对此的跟进:

other SO post

这是测试基于DataAnnotations的验证是否在控制器中起作用的好方法:

[Test]
public void UserController_CannotCreateUserWithNoLastName()
{
    // Arrange
    var user = new CreateUserViewModel();
    UsersController controller = new UsersController();
    var validationContext = new ValidationContext(user, null, null);
    var validationResults = new System.Collections.Generic.List<ValidationResult>();
    Validator.TryValidateObject(user, validationContext, validationResults);
    foreach (var validationResult in validationResults)
    {
    controller.ModelState.AddModelError("", validationResult.ErrorMessage);
    }

    // Act
    var result = controller.CreateUser(user);

    // Assert
    Assert.IsFalse(controller.ModelState.IsValid);
}

非常欢迎任何改进建议。我也想知道是否通常为每个验证/业务规则编写一个测试。谢谢!

1 个答案:

答案 0 :(得分:0)

您列出的代码是否基于here找到的内容?

就个人而言,我在每个注释的基础上编写这样的测试:

    [Test]
    public void CreateEventViewModel_Description_Property_Contains_StringLength_Attribute()
    {
        // Arrange
        PropertyInfo propertyInfo = typeof(CreateEventViewModel)
                                       .GetProperty("Description");
        // Act
        StringLengthAttribute attribute = propertyInfo
                      .GetCustomAttributes(typeof(StringLengthAttribute), true)
            .Cast<StringLengthAttribute>()
            .FirstOrDefault();

        // Assert
        Assert.NotNull(attribute);
        Assert.AreEqual(255, attribute.MaximumLength);
    }

我的基础是Brad Wilson发布的一些信息。这些测试与控制器测试分开存储。我不确定今天是否有更有效的方法可以做到这一点(有些人已经创建了更多的通用辅助方法来进行这种类型的测试;我只是希望自己对每个属性进行显式测试)但它会验证你的数据注释确实存在于视图模型上。

此类测试的组合,特别是验证属性,以及测试模型状态的测试,如上一个问题中所列

UsersController.ModelState.AddModelError("username", "Bad username"); 

是我通常会使用的。

相关问题