0

inside of the method which I'm evaluating in my Unit Test I want to return a mocked value which call my repository pattern, but always return null.

I've tried with both options below but the behavior is the same (return null):

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

and

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

I paste the whole code of my unit 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();
    }
}

I'm working with AutoFixture.AutoNSubstitute, NSubstite and NUnit

gogoru
  • 376
  • 2
  • 19
  • what exactly are you trying to test? – Andrei Dragotoniu Jun 27 '19 at 17:16
  • I want to return the user (mocked) on the update method for updated it – gogoru Jun 27 '19 at 22:38
  • 1
    @gogoru The two expressions passed from the test and from `SystemUnderTest` will be different (even if they do the same thing). Some options for dealing with this are described in answers to [this question](https://stackoverflow.com/q/5654053/906). – David Tchepak Jun 27 '19 at 23:20

1 Answers1

0

The solution is:

[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

gogoru
  • 376
  • 2
  • 19