【问题标题】:Unit Test with Nsubstitute allways return null with Lambda expression on Repository pattern使用 Nsubstitute 的单元测试总是在存储库模式上使用 Lambda 表达式返回 null
【发布时间】:2019-11-09 15:38:35
【问题描述】:

在我在单元测试中评估的方法内部,我想返回一个调用我的存储库模式的模拟值,但始终返回 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

【问题讨论】:

  • 你到底想测试什么?
  • 我想在更新方法上返回用户(模拟)以更新它
  • @gogoru 通过测试和SystemUnderTest 的两个表达式将不同(即使它们做同样的事情)。 this question 的回答中描述了一些处理此问题的选项。

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


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-14
    • 1970-01-01
    • 1970-01-01
    • 2020-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多