use*_*848 8 c# nunit unit-testing moq
我有以下控制器操作方法,我正在为此方法编写单元测试
try
{
if ( Session["token"] == null)
{
//checking whether the user has already given the credentials and got redirected by survey monkey by checking the query string 'code'
if (Request.QueryString["code"] != null)
{
string tempAuthCode = Request.QueryString["code"];
Session["token"] = _surveyMonkeyService.GetSurveyMonkeyToken(ApiKey, ClientSecret, tempAuthCode, RedirectUri, ClientId);
}
else
{
//User coming for the first time directed to authentication page
string redirectUrlToSurveyMonkeyAuthentication = _surveyMonkeyService.GetUrlToSurveyMonkeyAuthentication(RedirectUri, ClientId, ApiKey);
return Redirect(redirectUrlToSurveyMonkeyAuthentication);
}
}
//User is in the same session no need for token again showing surveys without authentication
var model = _surveyService.GetSurveys(User.Identity.Name);
if (model.Count == 0)
return View(CSTView.NoSurveyTracker.ToString());
return View(CSTView.Index.ToString(), model);
}
catch (Exception e)
{
return DisplayErrorView(e);//Even this returns a redirect method
}
Run Code Online (Sandbox Code Playgroud)
这是我为它编写的单元测试之一,
[Test]
public void GetIndexPage_Returns_View_With_ValidToken()
{
var mockControllerContext = new Mock<ControllerContext>();
var mockSession = new Mock<HttpSessionStateBase>();
mockSession.SetupGet(s => s["SurveyMonkeyAccessToken"]).Returns(SampleToken);
mockSession.SetupGet(c => c["code"]).Returns(SampleTempAuthCode);
mockControllerContext.Setup(p => p.HttpContext.Session).Returns(mockSession.Object);
_surveyTrackerController.ControllerContext = mockControllerContext.Object;
_surveyServiceMock.Setup(x => x.GetSurveys(TestData.TestData.SampleUserName)).Returns(SurveyTrackerList);
var result = _surveyTrackerController.GetIndexPage();
Assert.IsInstanceOf(typeof(ActionResult), result);
Assert.AreEqual(((ViewResult)result).ViewName, "expected");
}
Run Code Online (Sandbox Code Playgroud)
当我试图运行测试时抛出错误:对象引用没有设置为对象的实例,行号显示为request.querystring,如何在测试方法中设置会话变量,任何人都可以建议我是什么检查控制器动作返回类型的正确方法.
Dan*_*.G. 22
请求参数
您还需要模拟HttpRequestBase对象中的查询字符串.为此,您需要构建对象图
ControllerContext- > HttpContextBase- >HttpRequestBase
由于您已经在模拟ControllerContext控制器实例,因此可以使用以下代码添加模拟的查询字符串:
var queryString = new NameValueCollection { { "code", "codeValue" } };
var mockRequest = new Mock<HttpRequestBase>();
mockRequest.Setup(r => r.QueryString).Returns(queryString);
var mockHttpContext = new Mock<HttpContextBase>();
mockHttpContext.Setup(c => c.Request).Returns(mockRequest.Object);
mockControllerContext.Setup(c => c.HttpContext).Returns(mockHttpContext.Object);
Run Code Online (Sandbox Code Playgroud)
会议
对于模拟会话,使用上面配置的相同http上下文也返回模拟会话对象:
var mockSession = new Mock<HttpSessionStateBase>();
mockHttpContext.Setup(c => c.Session).Returns(mockSession.Object);
//where mockHttpContext has been created in the code for the queryString above and setup to be returned by the controller context
Run Code Online (Sandbox Code Playgroud)
然后,你可以设置的值,你没使用的方式SetupGet,或者你也可以使用Setup,如
mockSession.Setup(s => s["token"]).Returns("fooToken")
Run Code Online (Sandbox Code Playgroud)
如果要验证是否在会话中设置了值,可以在断言代码中添加以下内容:
mockSession.VerifySet(s => s["token"] = "tokenValue", Times.Once);
Run Code Online (Sandbox Code Playgroud)
ActionResult类型
我通常做的是使用as 运算符将结果转换为所需的类型.如果无法进行转换,它将返回null.因此断言可能如下所示:
ViewResult result = controller.Index() as ViewResult;
// Assert
Assert.IsNotNull(result);
Assert.AreEqual("fooView", result.ViewName);
Run Code Online (Sandbox Code Playgroud)
边注
如果您有许多类似的测试,其中代码使用会话和/或查询字符串,则每个测试都需要创建和配置相当多的模拟对象.
您可以在测试类中添加一个设置方法(在每次测试之前运行),并将所有使用模拟构建对象图的代码移动到那里.这样,每个测试方法都有一个全新的控制器实例,每个测试的安排部分只需要设置模拟行为和期望.
例如,如果您的测试类中有此安装代码:
private HomeController _homeController;
private Mock<HttpSessionStateBase> _mockSession;
private Mock<HttpRequestBase> _mockRequest;
[SetUp]
public void Setup()
{
_mockRequest = new Mock<HttpRequestBase>();
_mockSession = new Mock<HttpSessionStateBase>();
var mockHttpContext = new Mock<HttpContextBase>();
var mockControllerContext = new Mock<ControllerContext>();
mockHttpContext.Setup(c => c.Request).Returns(_mockRequest.Object);
mockHttpContext.Setup(c => c.Session).Returns(_mockSession.Object);
mockControllerContext.Setup(c => c.HttpContext).Returns(mockHttpContext.Object);
_homeController = new HomeController();
_homeController.ControllerContext = mockControllerContext.Object;
}
Run Code Online (Sandbox Code Playgroud)
每个测试的代码将减少到这样的代码:
[Test]
public void Index_WhenNoTokenInSession_ReturnsDummyViewAndSetsToken()
{
// Arrange
var queryString = new NameValueCollection { { "code", "dummyCodeValue" } };
_mockSession.Setup(s => s["token"]).Returns(null);
_mockRequest.Setup(r => r.QueryString).Returns(queryString);
// Act
ViewResult result = _homeController.Index() as ViewResult;
// Assert
Assert.IsNotNull(result);
Assert.AreEqual("dummy", result.ViewName);
_mockSession.VerifySet(s => s["token"] = "tokenValue", Times.Once);
}
[Test]
public void Index_WhenTokenInSession_ReturnsDefaultView()
{
// Arrange
_mockSession.Setup(s => s["token"]).Returns("foo");
// Act
ViewResult result = _homeController.Index() as ViewResult;
// Assert
Assert.IsNotNull(result);
Assert.AreEqual(String.Empty, result.ViewName);
}
Run Code Online (Sandbox Code Playgroud)
那些测试正在测试这种伪指数法
public ActionResult Index()
{
if (Session["token"] == null)
{
if (Request.QueryString["code"] != null)
{
Session["token"] = "tokenValue";
return View("dummy");
}
}
return View();
}
Run Code Online (Sandbox Code Playgroud)