Unit testing Asp。NETMVC4.5-如何对操作进行单元测试?

Unit testing Asp。NETMVC4.5-如何对操作进行单元测试?,unit-testing,asp.net-mvc-4,Unit Testing,Asp.net Mvc 4,在Asp.net MVC 4.5中,使用Microsoft.VisualStudio.TestTools.UnitTesting 是否有一种方法可以真正对操作结果进行单元测试?我看到的所有文档都只测试视图名称 Assert.AreEqual("Action Method", result.ViewName); 嗯,我想做一个真正的测试。如何测试控制器动作的响应?给出以下基本内容: public ActionResult Display(string productCode) {

在Asp.net MVC 4.5中,使用
Microsoft.VisualStudio.TestTools.UnitTesting

是否有一种方法可以真正对
操作结果进行单元测试?我看到的所有文档都只测试视图名称

Assert.AreEqual("Action Method", result.ViewName);

嗯,我想做一个真正的测试。如何测试控制器动作的响应?

给出以下基本内容:

    public ActionResult Display(string productCode)
    {
        var model = new ProductModel(productCode);

        if (model.NotFound)
        {
             return this.RedirectToRoute("NotFound");
        }

        return this.View("Product", model);
    }
而不是像
Assert.AreEqual(“操作方法”,result.ViewName)这样的断言(可以是有效的测试

你有很多选择,包括

查看模型类型

    [TestMethod]
    public void Display_WhenPassedValidProductCode_CreatesModel()
    {
        using (var controller = this.CreateController())
        {
            // Arrange Mocks on controller, e.g. a Service or Repository

            // Act
            var result = controller.Display(string.Empty) as ViewResult;
            var model = (ProductModel)result.Model;
            Assert.IsInstanceOfType(model, typeof(ProductModel));
        }
    }
查看模型总体过程

    [TestMethod]
    public void Display_WhenPassedValidProductCode_PopulatesModel()
    {
        using (var controller = this.CreateController())
        {
            const string ProductCode = "123465";
            // Arrange Mocks on controller, e.g. a Service or Repository

            // Act
            var result = controller.Display(ProductCode) as ViewResult;
            var model = (ProductModel)result.Model;
            Assert.AreEqual(ProductCode, model.ProductCode);
        }
    }
查看行动结果的类型

    [TestMethod]
    public void Display_WhenNotFound_Redirects()
    {
        using (var controller = this.CreateController())
        {
            const string ProductCode = "789000";
            // Arrange Mocks on controller, e.g. a Service or Repository

            // Act
            var result = controller.Display(ProductCode) as RedirectToRouteResult;
            Assert.IsNotNull(result); // An "as" cast will be null if the type does not match
        }
    }

基本上,你可以测试几乎任何东西,在你的代码库中选择一个示例并尝试测试它。如果你陷入困境,请构造一个像样的问题并将其发布到这里。

谢谢,使用NUNIT我无法得到HTML正文,这样我就可以测试正文的内容。使用MS工具,我看到我需要另一个项目来运行和测试信息技术