2013-10-11 246 views
0

我正在嘗試測試我的控制器,並且對於此測試頗爲新穎。使用NUnit和Moq我一直得到一個空結果。這是我的測試,我錯過了一個步驟?就像我提到這是我的第一個項目。MVC控制器單元測試

[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 = "[email protected]", 
      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); 
    } 

IREPOSITORY

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); 

    } 

回答

2

你的測試方法應該是這樣的:

[Test] 
public void CanCreateCustomer() 
{ 
    // ACT 
    var controller = new CustomerController(CustomerRepository.Object); 
    controller.Create(Customer); 

    // VERIFY 
    CustomerRepository.Verify(c => c.Add(It.Is.Any<Customer>(),Times.Once())); 
} 

的錯誤添加到你可以做到這一點像的ModelState這個:

controller .ModelState.AddModelError("key", "error message"); 

否則,modelState有效。

+0

謝謝!只需要弄清楚你如何聲明視圖。 :) – devfunkd

+0

你想測試什麼?視圖中的內容或您返回的視圖? – Rikard

+0

最終,但現在只是什麼觀點正在返回。 – devfunkd

0

要測試viewName,您需要稍微更改您的代碼。

[HttpPost] 
[ValidateAntiForgeryToken] 
public ActionResult Create(Customer customer) 
{ 
    if (ModelState.IsValid) 
    { 
     _customerRepository.Add(customer); 
     return RedirectToAction("Index"); 
    } 
    return View("Create", customer); 
} 

測試:

[Test] 
public void ReturnView() 
{ 
    // ACT 
    var controller = new CustomerController(CustomerRepository.Object); 
    var result = controller.Create(Customer); 

    // ASSERT 
    Assert.AreEqual("Create", ((ViewResult)result).ViewName); 
} 

要測試返回的數據:

[TestMethod] 
public void TestMethod2() 
{ 
    var controller = new CustomerController(); 
    var result = controller.Create(Customer); 

    Assert.AreEqual(1, ((Asd)((ViewResult)result).ViewData.Model).Id); 
}