0

How can I simulate this part of my code in xUnit

    var updateCost =
            await _costOfConsomption.DeferredWhere(x => x.Id == model.CostOfConsomptionId).FirstOrDefaultAsync() ??
            throw new
                NotFoundException();

this the DeferredWhere and FirstOrDefaultAsync must be simulated

1
  • xUnit is a unit testing framework, to "simulate" (i.e. mock) methods/ objects you'll need a mocking library, for example NSubstitute, or the somewhat controversial Moq
    – MindSwipe
    Commented Oct 16 at 6:22

2 Answers 2

0

We are not simulating the results of LINQ extension methods.

If your goal is to verify that NotFoundException is thrown when you didn't find the cost by id - then you need to encapsulate the search and simulate the output of that method.

0

FirstOrDefault is extension method, so it is static and cannot be mocked (well, at least easily, with just Moq).

And about mocking DeferredWhere, assuming that _costOfConsomption is of type ICostOfConsomption (interface), you can mock it using Moq library:

var costOfConsomptionMock = new Mock<ICostOfConsomption>();
costOfConsomptionMock
    .Setup(x => x.DeferredWhere(/* here you setup for what arguemnts mock will match */))
    .ReturnsAsync(/* here you setup DeferredWhere to return something or not */);

_costOfConsomption = costOfConsomptionMock.Object;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.