本文介绍了TDD Mock validate.ValidateAsync方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写单元测试,我们有一种方法,该方法通过传递 RuleSet 名称来调用手动验证.

I writing my unit test and we have method which call manual validation with passing RuleSet name.

我无法模拟我的 IValidator< RequestObj> .ValidateAsync()方法.

我使用的示例模拟语句

mockValidator.Setup(x => x.ValidateAsync(It.IsAny<SampleRequest>(), It.IsAny<CancellationToken>(), It.IsAny<IValidatorSelector>(), It.IsAny<string>()))
             .ReturnsAsync(new ValidationResult());

我遇到以下错误

请告诉我正确的方法.

推荐答案

您可以模拟Validate.ValidateAsync.

you can mock the Validate.ValidateAsync.

出现错误的原因是我尝试模拟扩展方法.谁的方法签名是

The Reason I was getting the error is I tried to mock an extension method. Whose method signature is

public static Task<ValidationResult> ValidateAsync<T>(this IValidator<T> validator, T instance, CancellationToken cancellationToken = default (CancellationToken), IValidatorSelector selector = null, string ruleSet = null)

但是,如果您看到它的实现,它将调用

But If you see its implementation it calls

validator.ValidateAsync((ValidationContext) validationContext, cancellationToken);

因此,根据上述签名创建Mock即可解决此问题.

So creating Mock based on the above signature solves the issue.

mockValidator.Setup(x => x.ValidateAsync(It.IsAny<ValidationContext>(), It.IsAny<CancellationToken>()))
                             .ReturnsAsync(new ValidationResult());

如果您要传递验证错误

mockValidator.Setup(x => x.ValidateAsync(It.IsAny<ValidationContext>(), It.IsAny<CancellationToken>()))
                             .ReturnsAsync(new ValidationResult(new List<ValidationFailure>()
                             {
                                 new ValidationFailure("TestField","Test Message"){ErrorCode = "1001"}
                             }));

这篇关于TDD Mock validate.ValidateAsync方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 11:33