我有一个方法,其操作取决于其依赖项,如下所示。进行单元测试仍然有价值吗?因为单元测试不是测试任何业务逻辑,而是通过模拟。
下面的单元测试:
请注意,该方法的选项由 确定expectedCustomerValidality
,由测试设置。大多数情况下,逻辑由模拟(例如Setup(c => c.IsValid())
.
[Test]
[TestCase(true)]
[TestCase(false)]
public void AddCustomer(bool expectedCustomerValidality)
{
//using Moq
companyRepositoryMock.Setup(c => c.GetById(It.IsAny<int>())).Returns(new Company());
customerValidatorMock.Setup(c => c.IsValid(It.IsAny<Customer>())).Returns(expectedCustomerValidality);
var customer = new Customer
{
Firstname = "firstName",
Surname = "surname",
Company = new Company { Id = 1 }
};
var addCustomer = customerServiceSut.AddCustomer(customer);
Assert.AreEqual(expectedCustomerValidality,addCustomer);
}
生产代码如下:
public class CustomerService : ICustomerService
{
private ICompanyRepository companyRepository;
private ICustomerRepository customerRepository;
private ICustomerValidator customerValidator;
public CustomerService(ICompanyRepository companyRepository, ICustomerRepository customerRepository, ICustomerValidator customerValidator)
{
this.companyRepository = companyRepository;
this.customerRepository = customerRepository;
this.customerValidator = customerValidator;
}
public bool AddCustomer(Customer customer)
{
customer.Company = companyRepository.GetById(customer.Company.Id); ;
if (customerValidator.IsValid(customer))
{
customerRepository.AddCustomer(customer);
return true;
}
return false;
}
}
问题:
- AddCustomer() 是否需要单元测试?
如果是这样,当前的单元测试是否以正确的方式执行?
1 如果不是,那么单元测试的正确方法是什么?