Search code examples
c#.net-corexunitfluent-assertionsfakeiteasy

FakeItEasy: Return NULL returning fakeiteasy null object thus if statement always passes checks


So i a xunit test method which goes into my Productorderservice to check if the a return value is null. However the returned object is never null as it returns a fakeiteasy null object even if i specify Fakeiteasy's .Returns method to return null.

var newproductionOrder = await _productionOrderRepository.CreateProductionOrder(newProduct,productionOrder);

if (newproductionOrder != null)
{
    await _productionOrderRepository.UpdateCounter();
    await _productRepository.UpdateCounter();
    return newproductionOrder;
}
throw new Exception("Failed to Create ProductionOrder");

my test code snippet

A.CallTo(() => fakePORepository.CreateProductionOrder(
        allProducts[0], invalidProductionOrder))
    .Returns(nullProductionOrder);

the null productionOrder was created by doing below

public static ProductionOrderDto? CreateNullProductionOrderDto()
{
    return null;
}

What am i doing wrong here?

Tried using return lazily to specify a customized way of return null. Yet it still returns the fakeiteasy object and my if statement runs while it doesn't have to run.


Solution

  • Without seeing how the types of allProducts[0] and invalidProductionOrder are defined, it's impossible to say. But your code generally looks good, so the most likely explanation is that the Equals methods are reference-based, not value-based, and the objects being passed in are not exactly the same instance that you're using to configure the fake.

    See Argument constraints - Matching values exactly for an explanation of FakeItEasy's "default" argument comparison.

    Debug through. Verify whether the Equals methods would return true for each argument.