通过autofac模拟之后,将调用服务的实际实现

时间:2019-09-19 17:32:00

标签: c# unit-testing moq autofac mstest

为项目编写单元测试用例,
服务类已被模拟,即使在模拟了实际的实现之后,也请提出正确模拟的方法。这样就可以正确模拟该服务方法。G




 [TestMethod]
    public void CustomerTest()
    {
      using (var mock = AutoMock.GetLoose())
      {
        //For testing,Created dummy object of customer having datatable dt
        var response = Task.FromResult(customer(dt))
        // Arrange - configure the mock
        mock.Mock<ICustomerService>().Setup(x => x.GetCustomerDetails(It.IsAny<string>(),It.IsAny<string>())).Returns(response);
        var sut = mock.Create<CustomerViewModel>();

        // Act
        var actual = sut.GetCustomerInfo("12345", "Name");

        // Assert - assert on the mock
        mock.Mock<ICustomerService>().Verify(x => x.GetCustomerDetails(It.IsAny<string>(),It.IsAny<string>(),Times.Once());
        Assert.AreEqual(response, actual);
      }
    }

我必须模拟服务,以免调用实际的服务方法。

2 个答案:

答案 0 :(得分:0)

将服务方法设为虚拟,这对NUnit来说是有用的。

答案 1 :(得分:0)

被嘲笑的成员似乎与您使用Task.FromResult作为响应的事实不同步

也可以让测试异步,并等待被测对象

[TestMethod]
public async Task CustomerTest() {
    using (var mock = AutoMock.GetLoose()) {
        //For testing,Created dummy object of customer having datatable dt
        var response = customer(dt);
        // Arrange - configure the mock
        mock.Mock<ICustomerService>()
            .Setup(_ => _.GetCustomerDetails(It.IsAny<string>(), It.IsAny<string>()))
            .ReturnsAsync(response);

        var sut = mock.Create<CustomerViewModel>();

        // Act
        var actual = await sut.GetCustomerInfo("12345", "Name");

        // Assert - assert on the mock
        mock.Mock<ICustomerService>()
            .Verify(_ => _.GetCustomerDetails(It.IsAny<string>(),It.IsAny<string>(), Times.Once());
        Assert.AreEqual(response, actual);
    }
}

以上假设模拟接口已明确注入被测对象

public class CustomerViewModel {

    public CustomerViewModel(ICustomerService service) {
        //...
    }

    //...

    public Task<Customer> GetCustomerInfo(string id, string name) {
        //...calls ICustomerService.GetCustomerDetails(id, name);
    }
}