MVC控制器单元测试

时间:2013-10-11 04:37:12

标签: c# asp.net-mvc unit-testing asp.net-mvc-4 nunit

我正在尝试测试我的控制器并对此测试很新。使用NUnit和Moq我一直得到一个null结果。这是我的考试,我错过了一步吗?就像我提到的那样,这是我的第一个项目。

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

CONTROLLER

// 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 个答案:

答案 0 :(得分: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()));
}

要向模型状态添加错误,您可以这样做:

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

否则modelState有效。

答案 1 :(得分: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);
 }