简体   繁体   中英

Unit test for controller in MVC.NET

I have following in my controller file:

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

I've to write Unit test case for CreateNewScan . How can this be done (preferably using built-in testing framework in VS)? Any pointers in this regard appreciated.

This should work, although for some reason on my workstation throws an error.

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

Please try and let me know. My PC has been acting up recently.

UPDATE

The PC was "acting up" because when using dynamic type, you must allow the test project to see the internals of your web application. So in your AssemblyInfo.cs of the web application, make sure you add this line:

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

where WebApplication1.Tests is the assembly name of your test project.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM