ton*_*9uk 2 tdd fluentvalidation
我正在尝试掌握 TDD,我已经查看了一些教程,并尝试对我使用 fluent 验证创建的验证类实施测试。
public SomeFormValidator()
{
RuleFor(x => x.MyClass).NotNull()
.WithMessage("MyClass cannot be null");
}
Run Code Online (Sandbox Code Playgroud)
我查看了专门用于流畅验证的 TDD 示例并创建了几个测试
[Test]
public void Should_have_error_when_MyClass_is_null()
{
MyClass myClass = null;
SomeFormValidator.ShouldHaveValidationErrorFor(aup => aup.MyClass, myClass);
}
[Test]
public void Should_not_have_error_when_MyClass_is_not_null()
{
MyClass myClass = new MyClass();
SomeFormValidator.ShouldNotHaveValidationErrorFor(aup => aup.MyClass, myClass);
}
Run Code Online (Sandbox Code Playgroud)
我现在想测试字符串“MyClass 不能为空”在它为空时返回。我无法找到任何涵盖返回消息的内容,也无法解决。
感谢@Surgey 的指导,我能够想出一个使用内置方法的流畅验证的解决方案,此外我已经能够更好地布局我在下面添加的测试
using FluentValidation.TestHelper;
using NUnit.Framework;
using MyProject.Models...
using MyProject...
namespace MyProject.Tests.Classes.Validation
{
[TestFixture]
public class SomeFormValidatorTest
{
private SomeFormValidator SomeFormValidator;
[SetUp]
public void Setup()
{
SomeFormValidator = new SomeFormValidator();
}
[Test]
public void Should_display_correct_error_message_MyClass_is_null()
{
//arrange
MyClass myClass = null;
//act
var result = SomeFormValidator.ShouldHaveValidationErrorFor(x => x.MyClass, myClass);
//assert
result.WithErrorMessage("MyClass is required");
//first attempt prior to finding WithErrorMessage exists
//foreach (var r in result)
//{
// Assert.AreEqual("MyClass is required", r.ErrorMessage);
//}
}
}
Run Code Online (Sandbox Code Playgroud)
}
我正在使用result.WithErrorMessage结果中提供的原样,但我已经保留了 foreach,但进行了评论,因为我发现使用Assert.AreEqual产生的错误消息在测试运行器中产生了更好的消息。