模拟Linq"任何"与Moq的谓词

Moh*_*our 3 c# linq unit-testing moq mocking

我正在尝试AnyAsync使用以下代码在我的存储库中模拟方法,但存储库总是返回false.

签名AnyAsync是:

Task<bool> AnyAsync<TEntity>(Expression<Func<TEntiry, bool>> predicate)
Run Code Online (Sandbox Code Playgroud)

我尝试了以下设置:

1:

mockCustomerRepository.Setup(r => r.AnyAsync(c => c.Email == "some@one.com"))
   .ReturnsAsync(true);
Run Code Online (Sandbox Code Playgroud)

2:

Expression<Func<CustomerEntity, bool>> predicate = expr => 
    expr.CustomerPerson.Email == "some@one.com";

mockCustomerRepository.Setup(r => r.AnyAsync(It.Is<Expression<Func<CustomerEntity, bool>>>
   (criteria => criteria == predicate))).ReturnsAsync(true);
Run Code Online (Sandbox Code Playgroud)

3:

mockCustomerRepository.Setup(r => r.AnyAsync(It.IsAny<Expression<Func<CustomerEntity, bool>>>()))
    .ReturnsAsync(true);
Run Code Online (Sandbox Code Playgroud)

我的测试:

public class Test 
{
    Mock<ICustomerRepository> mockCustomerRepository;

    public Test()
    {
        mockCustomerRepository = new Mock<ICustomerRepository>();
    }

    [Fact]
    public async Task CustomerTest()
    {   
        var customer = ObjectFactory.CreateCustomer(email: "some@one.com");
        var sut = new CustomerService(mockCustomerRepository.Object);

        var result = await sut.ValidateCustomerAsync(customer);
        .
        .
        .
    }
}
Run Code Online (Sandbox Code Playgroud)

我的CustomerService.ValidateCustomerAsync方法:

public async Task<OperationResult> ValidateCustomerAsync(CustomerEntity customer)
{
    var errors = new List<ValidationResult>();

    if (await _repository.AnyAsync(c => c.Email == customer.Email))
        errors.Add(new ValidationResult("blah blah")));
Run Code Online (Sandbox Code Playgroud)

我也读过这个,但它也不行.

Old*_*Fox 5

以下代码段显示了模拟AnyAsync方法的正确方法:

[TestMethod]
public async Task TestMethod1()
{
    var fakeCustomerRepo = new Mock<ICustomerRepository>();
    var foo = false;
    fakeCustomerRepo.Setup(repository => repository.AnyAsync(It.IsAny<Expression<Func<CustomerEntity, bool>>>()))
        .Callback<Expression<Func<CustomerEntity, bool>>>(
            expression =>
            {
                var func = expression.Compile();
                foo = func(new CustomerEntity() {Email = "foo@gmail.com"});
            })
        .Returns(() => Task.FromResult(foo));

    var customer = new CustomerEntity() {Email = "foo@gmail.com"};
    var result = await fakeCustomerRepo.Object.AnyAsync<CustomerEntity>(c => c.Email == customer.Email);
    Assert.IsTrue(result);

    customer = new CustomerEntity() { Email = "boo@gmail.com" };
    result = await fakeCustomerRepo.Object.AnyAsync<CustomerEntity>(c => c.Email == customer.Email);
    Assert.IsFalse(result);
}
Run Code Online (Sandbox Code Playgroud)

使用上面的设置,您可以验证作为单位行为一部分的谓词.