AJAY cHIGURUPATI AJAY cHIGURUPATI - 3 months ago 18
C# Question

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.

Answer

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