代码之家  ›  专栏  ›  技术社区  ›  K.Z

C#。如何测试我试图测试的同一类中的方法

  •  1
  • K.Z  · 技术社区  · 3 年前

    我班上有方法 CustomerServices 我需要模拟和测试。我不确定我的嘲笑是否正确?当代码命中时进行调试 customerService.Object.ProcessCustomer() 则它不调用实际的方法。

    如果方法是从其他类调用的,我知道如何在contractor中使用DI和引用对象进行模拟,但我不知道如何模拟我试图测试的同一类中存在的方法??

    我正在使用mock和autoFixture

    顾客

    public class Customer
    {
        public string Name { get; set; }
        public string Address { get; set; }
    }
    

    界面

    public interface ICustomerServices
    {
        List<Customer> GetCustomers();
        int ProcessCustomer();
    }
    

    客户服务

    public class CustomerServices : ICustomerServices
    {
        public CustomerServices()
        {
    
        }
    
        public int ProcessCustomer()
        {
            var customerList = GetCustomers();
    
            Console.WriteLine($"Total Customer Count {customerList.Count()}");
    
            return customerList.Count();
        }
    
        public List<Customer> GetCustomers()
        {
            return new List<Customer>();
        }
    }
    

    Test

    public class Tests
    {
        private readonly Mock<ICustomerServices> customerService;
    
        public Tests()
        {
            customerService = new Mock<ICustomerServices>();
        }
    
        [SetUp]
        public void Setup()
        {
        }
    
        [Test]
        public void Test1()
        {
            //Arrange 
            var fixture = new Fixture();
    
            var customerMoq = fixture.CreateMany<Customer>(5);
            customerService.Setup(_ => _.GetCustomers()).Returns((System.Collections.Generic.List<Customer>)customerMoq);
    
            //Act
            var actualResult = customerService.Object.ProcessCustomer();
    
            //Assert
        }
    }
    
    1 回复  |  直到 3 年前
        1
  •  0
  •   tmaj    3 年前

    您不应该嘲笑正在测试的服务。

    你的测试应该更像这样:

    [TestMethod]
    public void TestGetUser()
    {
        var mockLogger = new Mock<ILogger>(MockBehaviour.Strict);
        var mockSomeOtherDependency = new Mock<IA>(MockBehaviour.Strict);
    
        var beingTested = new UsersService(
            logger: mockLogger.Object
            someOtherDependency: mockSomeOtherDependency.Object,
            ...);
    
        mockSomeOtherDependency.Setup( r => r.GetCustomer("test")).Returns( new Customer(...));
    
        var r = beingTested.ProcessCustomer(); 
    
        Assert.IsNotNull(r);
    }