다음은 MOQ를 올바르게 사용 했습니까? 나는 "mocking", "stubbing", "faking"등등에 새롭고, 단지 내 머리를 감싸려고 노력합니다.단위 테스트에서 MOQ를 올바르게 사용하십시오.
이 모의는 알려진 결과를 제공한다는 것을 이해하기 때문에이 서비스를 사용하여이 서비스를 테스트하면 서비스가 제대로 반응합니까?
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