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