1

I am using NUnit to test my application with method as

      public int POCRemainingUnits()
    {

        var units = _transportService.GetUnits(x => x.Shipment.Id == shipmentId && x.POCAllowed == true && x.IsPOC == false, 0);
        int POCUnitCount = units.Count();

        //
        //
    }

And My test Method is something like

[Test]
        public void Invoke_POCUnitCommand_As_Many_Times_As_Number_Of_Remaining_Units_With_Valid_Input()
        {
            //arrange
            var unit1 = new Unit { IsPOC = false, POCAllowed = true };
            var unit2 = new Unit { IsPOC = false, POCAllowed = true };
            IQueryable<Unit> units = (new Unit[] { unit1, unit2 }).AsQueryable();



            _transportServiceMock.Setup(y => y.GetUnits(x => x.Shipment.Id == 1 && x.POCAllowed == true && x.IsPOC == false, 0)).Returns(units);


     //
     //
    }

But its failing as it is not setting the GetUnits methods.If I check the count in POCRemainingUnits, it still returns zero.Can anyone please suggest me what I am doing wrong.

Thanks In Advance

Yogendra Singh
  • 169
  • 1
  • 1
  • 10

2 Answers2

1

To setup mock, you need to write something like

transportServiceMock
    .Setup(ts => ts.GetUnits(It.IsAny<Func<Unit, bool>>(), It.IsAny<int>()))
    .Returns(units);
Alexander Stepaniuk
  • 6,217
  • 4
  • 31
  • 48
0

From my experience, mocking with lambdas as parameters doesn't work. Expressions that we would think of as being equal aren't actually equal.

For example:

[whatever].Where(x=>x.ShipmentId == 3);

is not seen as equal to

id = 3;
[whatever].Where(x=>x.ShipmentId == id);

My suggestion would be to either make a fake of your repository for testing, or isolate the queries and test them with integration tests.

See here

What you can do for getting the returns is something like

Where(Arg.Any<Expression<Func<Unit, bool>>>()).Returns(units);

Your testing of the lambda expression will have to happen another way. Either separate it into a separate method and integration test that method, or create a fake repository that you plug in and insert entities into that repository to grab from.

Community
  • 1
  • 1
CorrugatedAir
  • 809
  • 1
  • 6
  • 16