Nunit测试案例问题

时间:2016-06-17 11:39:59

标签: c# unit-testing nunit

我打算为我的MVC控制器编写单元测试用例。

我正在使用NUnit Framework。

这是我的Controller方法:

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

首先,我尝试验证视图名称,但是我遇到了从操作结果中获取视图名称的问题。

这是我的测试方法:

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

请告诉我如何模仿服务的响应。

2 个答案:

答案 0 :(得分:1)

我修复了问题,因为单元测试项目和Web项目中使用了不同版本的System.Web.MVC引用。

请确保单元测试项目和Web项目中引用的“System.Web.MVC”dll应该相同。

就我而言,Web-&gt; v4.0.0.0中使用的版本 单元测试项目中使用的版本 - > 4.0.0.1

我在单元测试项目中安装了版本'v4.0.0.0'并且它有效。

答案 1 :(得分:0)

以下是如何获取视图名称

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

您需要修改控制器以允许注入依赖项。 使用可注入接口,您可以使用像Moq这样的模拟框架为您的控制器生成模拟。

从您的示例中,以下是可以注入控制器的依赖项的良好候选项

  • _nmsPlatformClient
  • _helper