AMDI
AMDI

Reputation: 973

Nunit test Case issue

I am planning to write unit testcase for my MVC controller.

I am using NUnit Framework.

here is my Controller method:

public async Task<ActionResult> SearchView()
{
    List<Role> allRoles = (await _nmClient.GetDataAsync<IEnumerable<Role>>(Session, "/UserSvc/v1/Roles?skip=0&take=" + Constants.MaxSearchRowNumber)).ToList();
    model.Roles=_helper.GetAvailableRoles(Session.Contents["Session"], allRoles, true);
    List<LicenseType> allLicenseTypes = (await _Client.GetPlatformDataAsync<IEnumerable<LicenseType>>(Session, "/UserSvc/v1/Types?skip=0&take=" + Constants.MaxSearchRowNumber)).ToList();
    model.TypesJson = Newtonsoft.Json.JsonConvert.SerializeObject(allLicenseTypes);

    return View("SearchUsers", model);          
}

Here first I am trying to validate the view name,But I am facing issue with getting the view name from action result.

here is my Test Method:

[Test]
public void TestSearchUserView() 
{ 
    string expected= "SearchUserView"; 
    PlatformUserController controller = new PlatformUserController(); 
    var result= controller.SearchUserView() as Task<ActionResult>; 
            
    //Assert.AreEqual("SearchUserView", result.);  
}

Please let me know how can I mock the response of service as well.

Upvotes: 0

Views: 102

Answers (2)

AMDI
AMDI

Reputation: 973

I got the issue fixed, its because of different versions of System.Web.MVC reference used in Unit Test project and Web project.

Please make sure 'System.Web.MVC' dll referenced in both Unit Test project and Web Project should be same.

In my case, the version used in Web->v4.0.0.0 the version used in Unit Test Project->4.0.0.1

I installed the version 'v4.0.0.0' in Unit Test Project and it worked.

Upvotes: 1

Nkosi
Nkosi

Reputation: 247088

Here is an example of how to get the View name

[TestMethod]
public async Task TestSearchUserView() {
    //Arrange
    string expected = "SearchUsers";
    var controller = new PlatformUserController();

    //Act
    var actionResult = await controller.SearchUserView();

    //Assert
    Assert.IsNotNull(actionResult);
    var viewResult = actionResult as ViewResult;
    Assert.IsNotNull(viewResult);
    Assert.AreEqual(expected, viewResult.ViewName);  
} 

You will need to modify your controller to allow dependencies to be injected. with injectable interfaces, you can use a mocking framework like Moq to generate mocks for your controller.

From your example the following are good candidates for dependencies that can be injected into the controller

  • _nmsPlatformClient
  • _helper

Upvotes: 0

Related Questions