控制器在MVC.NET中的单元测试

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

我有以下在我的控制器文件:

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)?

控制器在MVC.NET中的单元测试

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

    [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"出问题"是因为当使用动态类型时,你必须允许测试项目看到你的web应用程序的内部。因此,在web应用程序的AssemblyInfo.cs中,确保添加了这一行:

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

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