ASP.NET控制器unittest使用Moq验证错误

时间:2016-12-20 09:06:05

标签: c# asp.net unit-testing moq

我正在使用asp.net web api构建api服务。我尝试使用moq测试我的控制器,但是我收到以下错误

  

模拟上的预期调用至少一次,但从来没有   执行:x => x.CreateIncome())

这是下面的测试

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

此控制器中使用的服务将注入我下面显示的IncomeController

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 个答案:

答案 0 :(得分:3)

问题在于您尝试使用Post对象进行验证,但在Income方法中,您实例化了_incomeServiceMock.Verify(x => x.CreateIncome(It.IsAny<Income>())); 的不同实例并将其传递给服务。这些情况不一样。

您可以将验证声明更改为

_incomeServiceMock.Verify(x => x.CreateIncome(It.Is<Income>(inc=>
    inc.Description == newIncome.Description 
    && inc.Amount == newIncome.Amount 
    && inc.StuffId == newIncome.StuffId)));

serie.Value.Values.Distinct().Count();