首页 > 解决方案 > 通过 autofac 模拟后,服务的实际实现被调用

问题描述

我正在为项目编写单元测试用例,
服务类被模拟,甚至在模拟实际实现之后被调用,请建议正确模拟的方法。这样服务方法就被正确地模拟了。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);
      }
    }

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

标签: c#unit-testingmoqautofacmstest

解决方案


使服务方法虚拟化,这对我来说对 NUnit 有用。


推荐阅读