0

我正在尝试测试我的控制器,并且对这个测试很陌生。使用 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);

    }
4

2 回答 2

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

否则模型状态是有效的。

于 2013-10-11T07:27:10.303 回答
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);
 }
于 2013-10-11T18:23:13.040 回答