简体   繁体   English

使用ASP.NET MVC 3 +数据注释和属性DateTime进行单元测试

[英]Unit Testing with ASP.NET MVC 3 + Data Annotations and property DateTime

I'm on a project with DataAnnotations and ASP.NET MVC3. 我正在使用DataAnnotations和ASP.NET MVC3的项目。 We use this solution to test the validations of "Date Annotions": http://gcbyjm.blogspot.com.br/2011/02/how-to-unit-test-dataannotations.html 我们使用此解决方案来测试“日期注释”的验证: http ://gcbyjm.blogspot.com.br/2011/02/how-to-unit-test-dataannotations.html

I have problems to test a property "DateTime" of "ViewModel". 我在测试“ ViewModel”的属性“ DateTime”时遇到问题。

public class AchievementVM
{
    ...

    [Required(ErrorMessage = "The date field is required.")]
    [DataType(DataType.DateTime, ErrorMessage = "Invalid date.")]
    public DateTime Date { get; set; }

    ...
}

    [TestMethod]
    public void AchievementVMValidator_ShouldHaveErrorWhenDateIsInvalid()
    {
        // Arrange
        var achievementVM = new AchievementVM() { Date = ???? };

        // Act
        var errors = ValidationBuddy.GetErrors(achievementVM) as List<ErrorInfo>;

        // Assert
        ErrorInfo error = errors.Find(delegate(ErrorInfo e) { return e.ErrorMessage == "The date field is required."; });
        Assert.IsTrue(error != null);
    }

My question is how to pass the value of this property to simulate the ModelBind ERROR. 我的问题是如何传递此属性的值来模拟ModelBind ERROR。 In both situations, textbox empty and invalid data. 在两种情况下,文本框均为空且数据无效。

Thanks a lot! 非常感谢!

If I understand your question correctly I think you should be testing action method that gets called by the view where the field is located. 如果我正确理解了您的问题,我认为您应该测试该字段所在的视图调用的操作方法。 Like that you can pass invalid or empty values to the action method replicating empty or invalid values. 这样,您可以将无效或空值传递给复制空或无效值的操作方法。

Remember that your view-model should be a representation of your view. 请记住,您的视图模型应代表您的视图。 So if your view allows a DateTime to not be entered (empty text box) then I think your view-model should have a nullable DateTime. 因此,如果您的视图允许不输入 DateTime(空文本框),那么我认为您的视图模型应具有可为空的DateTime。

public DateTime? MyProperty { get; set; }

That way, in your unit test you can test for a null DateTime. 这样,在单元测试中,您可以测试空的DateTime。

On your domain model this should be different as you dont want your database to receive a null DateTime so the domain model property should not be nullable. 在您的域模型上,这应该有所不同,因为您不希望数据库接收到空的DateTime,因此域模型属性不应为空。 you view-model validation should stop the null date getting passed to the domain model or something converts it to a DateTime the domain model can handle. 您的视图模型验证应停止将空日期传递给域模型,或者将其转换为域模型可以处理的DateTime。 Maybe, for example, a null DateTime gets converted to DateTime.Now if your business requirements match this. 例如,也许您将空的DateTime转换为DateTime。现在,如果您的业务需求与此匹配。

I hope this helps. 我希望这有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM