TDD 模拟 validate.ValidateAsync 方法
TDD Mock validate.ValidateAsync method
我正在编写我的单元测试,我们有通过传递 RuleSet
名称调用手动验证的方法。
我无法模拟我的 IValidator<RequestObj>.ValidateAsync()
方法。
我使用的示例模拟语句
mockValidator.Setup(x => x.ValidateAsync(It.IsAny<SampleRequest>(), It.IsAny<CancellationToken>(), It.IsAny<IValidatorSelector>(), It.IsAny<string>()))
.ReturnsAsync(new ValidationResult());
我收到以下错误
Invalid setup on an extension method: x =>
x.ValidateAsync(It.IsAny(),
It.IsAny(), It.IsAny(),
It.IsAny()) at
Moq.Mock.ThrowIfSetupExpressionInvolvesUnsupportedMember(Expression
setup, MethodInfo method)
请告诉我正确的方法。
你可以模拟 Validate.ValidateAsync。
我收到错误的原因是我试图模拟扩展方法。谁的方法签名是
public static Task<ValidationResult> ValidateAsync<T>(this IValidator<T> validator, T instance, CancellationToken cancellationToken = default (CancellationToken), IValidatorSelector selector = null, string ruleSet = null)
但是如果你看到它的实现,它会调用
validator.ValidateAsync((ValidationContext) validationContext, cancellationToken);
所以根据上面的签名创建 Mock 就解决了这个问题。
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"}
}));
我正在编写我的单元测试,我们有通过传递 RuleSet
名称调用手动验证的方法。
我无法模拟我的 IValidator<RequestObj>.ValidateAsync()
方法。
我使用的示例模拟语句
mockValidator.Setup(x => x.ValidateAsync(It.IsAny<SampleRequest>(), It.IsAny<CancellationToken>(), It.IsAny<IValidatorSelector>(), It.IsAny<string>()))
.ReturnsAsync(new ValidationResult());
我收到以下错误
Invalid setup on an extension method: x => x.ValidateAsync(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny()) at Moq.Mock.ThrowIfSetupExpressionInvolvesUnsupportedMember(Expression setup, MethodInfo method)
请告诉我正确的方法。
你可以模拟 Validate.ValidateAsync。
我收到错误的原因是我试图模拟扩展方法。谁的方法签名是
public static Task<ValidationResult> ValidateAsync<T>(this IValidator<T> validator, T instance, CancellationToken cancellationToken = default (CancellationToken), IValidatorSelector selector = null, string ruleSet = null)
但是如果你看到它的实现,它会调用
validator.ValidateAsync((ValidationContext) validationContext, cancellationToken);
所以根据上面的签名创建 Mock 就解决了这个问题。
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"}
}));