【问题标题】:Unit test for controller in MVC.NETMVC.NET 中控制器的单元测试
【发布时间】:2014-07-30 22:16:23
【问题描述】:

我的控制器文件中有以下内容:

public ActionResult Index()
{
    var model = new ClientGroupIndexViewModel()
    {
        AddScanUrl = Url.RouteUrl<ClientGroupsController>(c => c.CreateNewScan(null, null)),
        //other similar stuff
    };

    return View("ClientGroupsIndex", model);
}


public JsonResult CreateNewScan(ClientGroup clientGroup, Version version)
{
    //do something
    return Json(new{Message = "created new scan", Success = true});
}

我要为 CreateNewScan 编写单元测试用例。如何做到这一点(最好使用 VS 中的内置测试框架)?任何这方面的指针表示赞赏。

【问题讨论】:

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


【解决方案1】:

这应该可以工作,尽管由于某种原因在我的工作站上引发了错误。

    [TestMethod]
    public void CreateNewScan()
    {
        HomeController controller = new HomeController();
        ClientGroup clientGroup = new ClientGroup(){ 
            //some property initializers
        };
        JsonResult result = controller.CreateNewScan(clientGroup, new Version(1, 0));
        dynamic data = result.Data;
        Assert.IsTrue(data.Success);
    }

请尝试告诉我。我的电脑最近出现故障。

更新

PC 正在“行动起来”,因为when using dynamic type, you must allow the test project 可以查看您的 Web 应用程序的内部结构。因此,在 Web 应用程序的 AssemblyInfo.cs 中,请确保添加以下行:

[assembly: InternalsVisibleTo("WebApplication1.Tests")]

其中WebApplication1.Tests 是您的测试项目的程序集名称。

【讨论】:

  • 感谢您的努力。对不起,如果这是一个愚蠢的问题,但它也要求 [UrlToTest()]。我知道这里有一些 url 路由。我在浏览器中看到的那个是不可接受的。如何找到正确的 URL 进行测试?
  • 你的意思是如何测试Index()?
  • 没关系,反正是个愚蠢的问题。这工作:) 非常感谢。
猜你喜欢
  • 1970-01-01
  • 2016-07-06
  • 1970-01-01
  • 2020-08-12
  • 2017-06-26
  • 2011-12-01
  • 2014-01-16
  • 1970-01-01
相关资源
最近更新 更多