MVC 控制器单元测试

本文关键字:单元测试 控制器 MVC | 更新日期: 2023-09-27 18:34:47

>我正在尝试测试我的控制器,并且对这个测试很陌生。使用 NUnit 和最小起订量,我不断得到一个空结果。这是我的测试,我错过了一步吗?就像我提到的,这是我的第一个项目。

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

MVC 控制器单元测试

您的测试方法应如下所示:

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

否则,模型状态有效。

要测试 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);
 }