[英]Verify Expression<Func<T, bool>> argument in a unit test with NSubstitute
I'm working on a unit test and I'd like to verify that a mock object received the proper predicate argument.我正在进行单元测试,我想验证模拟对象是否收到了正确的谓词参数。 However, I fail to make it work.
但是,我无法让它发挥作用。
Here's a skeleton of the code:这是代码的骨架:
public interface IRepository<T>
{
Task<T> SingleOrDefaultAsync(Expression<Func<T, bool>> predicate);
}
public class MyClass
{
private readonly IRepository<Foo> _repository
public MyClass(IRepository<Foo> repository)
{
_repository = repository;
}
public Task<bool> MyMethod(int id)
{
var foo = _repository.SingleOrDefaultAsync(x => x.Id == id);
return foo != null;
}
}
and in my test class I have the following method在我的测试课中,我有以下方法
public async Task MyTestMethod()
{
var repository = Substitute.For<IRepository<Foo>>();
repository.SingleOrDefaultAsync(x => x.Id == 123).Returns(Task.FromResult(new Foo()));
var myClass = new MyClass(repository);
var result = await myClass.MyMethod(123);
result.Should().BeTrue();
}
But as mentioned above, this test fails.但是如上所述,这个测试失败了。 I could make it pass by using
Arg.Any<Expression<Func<Foo, bool>>
, but it doesn't feel right.我可以通过使用
Arg.Any<Expression<Func<Foo, bool>>
让它通过,但感觉不对。
Anyone has a suggestion what I'm doing wrong?任何人都有建议我做错了什么?
Capture the expression passed to the mock and use it in the Returns
to verify the expected behavior.捕获传递给模拟的表达式并在
Returns
使用它来验证预期的行为。
For example例如
public async Task MyTestMethod() {
//Arrange
var id = 123;
var model = new Foo() {
Id = id;
}
var repository = Substitute.For<IRepository<Foo>>();
repository.SingleOrDefaultAsync(Arg.Any<Expression<Func<Foo, bool>>())
.Returns(args => {
var expression = args.Arg<Expression<Func<Foo, bool>>(); //capture expression
Foo result = expression.Compile()(model) ? model : null; //use to verify behavior
Task.FromResult(result);
});
var myClass = new MyClass(repository);
//Act
var actual = await myClass.MyMethod(id);
//Assert
actual.Should().BeTrue();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.