【问题标题】:Unit tests with FluentValidation. How to mock ValidationResult使用 FluentValidation 进行单元测试。如何模拟 ValidationResult
【发布时间】:2016-06-15 08:43:16
【问题描述】:

我将 TDD 方法与 xUnit 2、NSubstitute、AutoFixture、FluentAssertions 一起用于我的单元测试。

我想测试使用 FluentValidation 的服务方法。

简单示例:

验证器:

RuleSet("Nulls", () =>
        {
            RuleFor(viewModel => viewModel).NotNull();
        });

我的服务(正在测试中):

if(Validate(viewModel, "Nulls"))
//....
private bool Validate(AddMerchantViewModel viewModel, string option)
{
    var result = _merchantValidator.Validate(viewModel, ruleSet: options);
    return result.IsValid;
}

还有我的单元测试:

我不知道如何模拟 merchantValidator.Validate 结果。

[Theory, AutoNSubstituteData]
public void Add_ViewModelAsNull_ShouldThrowArgumentNullException(
    AbstractValidator<AddMerchantViewModel> merchValidator,
    MerchantsService service)
{
    // Arrange


    //here I don't know how to mock result of Validate. It is always null.
    merchantValidator.Validate(Arg.Any<AddMerchantViewModel>(), ruleSet: Arg.Any<string>()).Return(new ValidationResult()); 



    // Act
    Action action = () => service.Add(null);

    // Assert
    action.ShouldThrow<ArgumentNullException>();
} 

【问题讨论】:

    标签: unit-testing xunit fluentvalidation autofixture nsubstitute


    【解决方案1】:

    默认情况下,AutoFixture 在每次请求时都会创建一个类型的新实例。在这种特殊情况下,AbstractValidator&lt;AddMerchantViewModel&gt; 类型被实例化了两次 - 作为 merchValidator 参数和 MerchantsService 类的依赖项。

    因此,服务不使用配置的验证器。为了解决这个问题,您应该使用[Frozen] 属性装饰merchValidator 参数,以便AF 始终返回AbstractValidator&lt;AddMerchantViewModel&gt; 类型的相同实例:

    [Theory, AutoNSubstituteData]
    public void Add_ViewModelAsNull_ShouldThrowArgumentNullException(
        [Frozen]AbstractValidator<AddMerchantViewModel> merchValidator,
        MerchantsService service)
    // ...
    

    更多关于[Frozen]属性的信息可以在here找到。

    【讨论】:

      猜你喜欢
      • 2018-04-04
      • 2021-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-19
      • 1970-01-01
      • 2012-02-16
      相关资源
      最近更新 更多