C#。如何测试我正在尝试测试的同一类中的方法
我的类 CustomerServices
中有需要模拟和测试的方法。我不确定我是否正确嘲笑?在调试中,当代码命中 customerService.Object.ProcessCustomer()
时,它不会调用实际方法。
如果这些方法是从其他类调用的,我知道如何通过在承包商中使用 DI 和引用对象来进行模拟,但我不知道如何模拟我正在尝试测试的同一类中存在的方法?
我正在使用模拟和 autoFixture
客户
public class Customer
{
public string Name { get; set; }
public string Address { get; set; }
}
接口
public interface ICustomerServices
{
List<Customer> GetCustomers();
int ProcessCustomer();
}
CustomerService
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
}
}
I have methods in my class CustomerServices
that I need to mock and test. I am not sure If I am mocking correctly? In debugging when code hit customerService.Object.ProcessCustomer()
then it do not call actual method.
If the methods are calling from other class I know how to mock by using DI and reference object in contractor but I not getting how I can mock method that exist in same class that I am trying to test??
I am using mock and autoFixture
Customer
public class Customer
{
public string Name { get; set; }
public string Address { get; set; }
}
Interface
public interface ICustomerServices
{
List<Customer> GetCustomers();
int ProcessCustomer();
}
CustomerService
public class CustomerServices : ICustomerServices
{
public CustomerServices()
{
}
public int ProcessCustomer()
{
var customerList = GetCustomers();
Console.WriteLine(quot;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
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您不应该嘲笑正在测试的服务。
你的测试应该看起来更像这样:
You should not mock the service that is being tested.
Your test should look more like this: