C# Moq 方法摘要 class

C# Moq method in abstract class

谁能告诉我如何模拟基本抽象中方法的结果 class?请参阅下面非常基本的示例代码来演示问题,我需要模拟“GetAge()”方法的结果。请参阅末尾的注释行,结尾为“<----- FIX here”,我认为需要在此处添加修复程序。

客户服务

public interface ICustomerService
{
    string GetCustomerDetailsSrv(int age);
}

public class CustomerService : ICustomerService
{
    public string GetCustomerDetailsSrv(int age)
    {
        return $"Name: John Doe. Age: {age}";
    }
}

基地控制器

public abstract class MyBaseController : ControllerBase
{
    public virtual int GetAge()
    {
        return 7;
    }
}

客户控制员

public class CustomerController : MyBaseController
{
    private readonly ICustomerService _customerSrv;

    public CustomerController(ICustomerService customerSrv)
    {
        _customerSrv = customerSrv;
    }

    
    [HttpGet]
    public string GetCustomerDetails()
    {
        var age = GetAge();
        var result = _customerSrv.GetCustomerDetailsSrv(age);
        return result;
    }
}

客户控制器测试

[TestClass]
public class CustomerControllerTest
{
    private readonly CustomerController _controller;
    private readonly Mock<ICustomerService> _mockSrv;

    public CustomerControllerTest()
    {
        _mockSrv = new Mock<ICustomerService>();
        _controller = new CustomerController(_mockSrv.Object);
    }

    [TestMethod]
    public void TestGet()
    {
        //Arrange
        int mockAge = 11;
        string expectedResult = $"Name: Alice Smith. Age: {mockAge}";
        // _controller.Setup(Controller => Controller.GetAge()).Returns(mockAge); <----- FIX here
        _mockSrv.Setup(repo => repo.GetCustomerDetailsSrv(mockAge)).Returns(expectedResult); 

        //Act
        var actualResult = _controller.GetCustomerDetails();

        //Assert
        Assert.IsTrue(actualResult == expectedResult);
    }
}

我认为下面的代码可以实现你想要的。

CustomerController 创建 Mock 允许设置虚拟方法 GetAge,同时仍然能够使用 CustomerControllerGetCustomerDetails 方法class.

[TestClass]
public class CustomerControllerTest
{
    private readonly Mock<CustomerController> _mockController;
    private readonly Mock<ICustomerService> _mockSrv;

    public CustomerControllerTest()
    {
        _mockSrv = new Mock<ICustomerService>();
        _mockController = new Mock<CustomerController>(() => new CustomerController(_mockSrv.Object));
    }

    [TestMethod]
    public void TestGet()
    {
        //Arrange
        int mockAge = 11;
        string expectedResult = $"Name: Alice Smith. Age: {mockAge}";
        _mockController.Setup(Controller => Controller.GetAge()).Returns(mockAge);
        _mockSrv.Setup(repo => repo.GetCustomerDetailsSrv(mockAge)).Returns(expectedResult);

        //Act
        var actualResult = _mockController.Object.GetCustomerDetails();

        //Assert
        Assert.IsTrue(actualResult == expectedResult);
    }
}