带有Nsubstitute的单元测试始终在存储库模式上返回带有Lambda表达式的null

时间:2019-06-27 15:08:11

标签: unit-testing .net-core nunit autofixture nsubstitute

在单元测试中评估的方法内,我想返回一个模拟值,该值调用存储库模式,但始终返回null。

我已经尝试过以下两个选项,但行为相同(返回null):

Repository.FindAsync<User>(Arg.Is<Expression<Func<User, bool>>>(x => x.Email == "Test")).Returns(new User() { FirstName = "Test"});

Repository.FindAsync<User>(x => x.Email == "Test").Returns(new User() { FirstName = "Test"});

我粘贴了单元测试的全部代码

public class WhenTestingUser : WhenTesting<Customer>
{
    private IRepository Repository { get; set; }

    protected override void Given()
    {
        Repository = Fixture.Freeze<IRepository>();

        Repository.Find<User>(Arg.Any<Expression<Func<User, bool>>>()).ReturnsNull();

        Repository.FindAsync<User>(Arg.Is<Expression<Func<User, bool>>>(x => x.Email == "Test")).Returns(new User() { FirstName = "Test"});


    }

    protected override void When()
    {

        SystemUnderTest.UpdateUser().GetAwaiter();

    }

    [Test]
    public void WhenCalled()
    {
        throw new NotImplementedException();
    }
}

我正在使用AutoFixture.AutoNSubstitute,NSubstite和NUnit

1 个答案:

答案 0 :(得分:-1)

解决方案是:

[Test]
public void TestUnprocessedInvoicesByCatchingExpression()
{
    Expression<Func<InvoiceDTO, bool>> queryUsed = null;
    IList<InvoiceDTO> expectedResults = new List<InvoiceDTO>();
    _invoiceRepository
    .Find(i => true)
    .ReturnsForAnyArgs(x =>
    {
        queryUsed = (Expression<Func<InvoiceDTO, bool>>)x[0];
        return expectedResults;
    });

    Assert.That(_sut.GetUnprocessedInvoices(), Is.SameAs(expectedResults));
    AssertQueryPassesFor(queryUsed, new InvoiceDTO { IsProcessed = false, IsConfirmed = true });
    AssertQueryFailsFor(queryUsed, new InvoiceDTO { IsProcessed = true, IsConfirmed = true });
}

NSubstitute - Testing for a specific linq expression