【发布时间】:2013-08-16 23:31:00
【问题描述】:
鉴于以下情况,这是正确使用最小起订量吗?我对“嘲笑”、“存根”、“假装”等很陌生,只是想把头绕过去。
我的理解是这个模拟提供了一个已知的结果,所以当我使用它测试这个服务时,服务会正确反应吗?
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。
【问题讨论】:
-
测试对我来说很好。用例的有效测试。
-
我建议您让测试名称代表正在测试的内容。让您稍后回到测试时更容易理解。因此,不要将“Test1”称为“CannotCreateACustomerWithSameIdAsExistingCustomer”
标签: c# unit-testing moq xunit xunit.net