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);
}