我正在尝试测试我的控制器,并且对这个测试很陌生。使用 NUnit 和 Moq 我不断得到空结果。这是我的测试,我错过了一步吗?就像我提到的那样,这是我的第一个项目。
[TestFixture]
class CustomerServiceTests
{
public Mock<IRepository<Customer>> CustomerRepository = new Mock<IRepository<Customer>>();
public Customer Customer;
[SetUp]
public void Setup()
{
Customer = new Customer()
{
Id = 1 << Can I set the ID?
Address = "3 Lakeview Terrace",
City = "New York",
Email = "someone@email.com",
FirstName = "Joe",
LastName = "Dirt",
Phone = "888-888-8888",
Province = "NY"
};
}
[Test]
public void CanCreateCustomer()
{
// ARRANGE
var controller = new CustomerController(CustomerRepository.Object);
controller.Create(Customer);
// ACT
var customer = CustomerRepository.Setup(c => c.Find(1)).Returns(new Customer());
// ASSERT
Assert.AreEqual(Customer, customer);
}
}
控制器
// POST: /Customer/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Customer customer)
{
if (ModelState.IsValid)
{
_customerRepository.Add(customer);
return RedirectToAction("Index");
}
return View(customer);
}
存储库
public interface IRepository<T> where T : class
{
IQueryable<T> Get { get; }
T Find(object[] keyValues);
T Find(int id);
void Add(T entity);
void Update(T entity);
void AddOrUpdate(T entity);
void Remove(object[] keyValues);
void Remove(T entity);
}