鉴于以下情况,是否适当使用起订量?我对“嘲笑”,“磕磕绊绊”,“伪装”等方面都很陌生,只是想把头围绕在它周围。在单元测试中正确使用最小起订量
我的理解是,这个模拟提供了一个已知的结果,所以当我使用它来测试这个服务时,服务反应是否正确?
public interface IRepository<T> where T : class
{
void Add(T entity);
void Delete(T entity);
void Update(T entity);
IQueryable<T> Query();
}
public interface ICustomerService
{
void CreateCustomer(Customer customer);
Customer GetCustomerById(int id);
}
public class Customer
{
public int Id { get; set; }
}
public class CustomerService : ICustomerService
{
private readonly IRepository<Customer> customerRepository;
public CustomerService(IRepository<Customer> customerRepository)
{
this.customerRepository = customerRepository;
}
public Customer GetCustomerById(int id)
{
return customerRepository.Query().Single(x => x.Id == id);
}
public void CreateCustomer(Customer customer)
{
var existingCustomer = customerRepository.Query().SingleOrDefault(x => x.Id == customer.Id);
if (existingCustomer != null)
throw new InvalidOperationException("Customer with that Id already exists.");
customerRepository.Add(customer);
}
}
public class CustomerServiceTests
{
[Fact]
public void Test1()
{
//var repo = new MockCustomerRepository();
var repo = new Mock<IRepository<Customer>>();
repo.Setup(x => x.Query()).Returns(new List<Customer>() { new Customer() { Id = 1 }}.AsQueryable());
var service = new CustomerService(repo.Object);
Action a =() => service.CreateCustomer(new Customer() { Id = 1 });
a.ShouldThrow<InvalidOperationException>();
}
}
我正在使用xUnit,FluentAssertions和MOQ。
测试对我来说看起来很好。用例的有效测试。 – labroo
我建议的一件事就是你让测试名称代表正在测试的内容。让您在稍后再回来测试时更容易理解。所以,而不是“Test1”称之为“CannotCreateACustomerWithSameIdAsExistingCustomer” – Caleb