1

I'm building an api service using asp.net web api. I'm trying to test my controller using moq but i get the following error

Expected invocation on the mock at least once, but was never performed: x =>x.CreateIncome())

This is the test below

[TestClass]
public class IncomeControllerTests
{
    private Mock<IIncomeService> _incomeServiceMock;
    [TestInitialize]
    public void BeforeEachTest()
    {
        _incomeServiceMock = new Mock<IIncomeService>();

        _incomeServiceMock
            .Setup(x => x.CreateIncome(It.IsAny<Income>())).Verifiable();
    }

    [TestMethod]
    public void Income_Is_Saved_Successfully()
    {
        var incomeController = new IncomeController(_incomeServiceMock.Object);
        Income newIncome = {
            Description = "Income1",
            Amount = 22300,
            Id = 221,
            StaffId = sampleManager.Id,
            Staff = sampleManager,
            DateCreated = DateTime.Now
        }

        incomeController.Post(newIncome);
        _incomeServiceMock.Verify(x => x.CreateIncome(newIncome));
    }
}

The service used in this controller is injected into my IncomeController shown below

IncomeController.cs

[Authorize]
public class IncomeController : ApiController
{
    private IIncomeService _incomeService;
    public IncomeController(IIncomeService service)
    {
        _incomeService = service;
    }

    public void Post([FromBody]Income values)
    {
        Income income = new Income(
            values.Description,
            values.Amount,
            values.StaffId
            );

        _incomeService.CreateIncome(income);
    }
}

IIncomeService.cs

public interface IIncomeService
{
    void CreateIncome(Income income);
    Income GetIncome(int id);
    List<Income> GetAllIncome();
    Dictionary<string, int> GetMonthlyIncome();
    Dictionary<string, int> GetYearlyIncome();
    void Update(Income income);
}

1 Answer 1

3

The problem is that you are trying to verify using newIncome object but in Post method you instantiated different instance of the Income and pass that to service. These instances are not the same.

You can change your verify statement to something like

_incomeServiceMock.Verify(x => x.CreateIncome(It.IsAny<Income>()));

or

_incomeServiceMock.Verify(x => x.CreateIncome(It.Is<Income>(inc=>
    inc.Description == newIncome.Description 
    && inc.Amount == newIncome.Amount 
    && inc.StuffId == newIncome.StuffId)));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.