【发布时间】:2014-04-14 05:50:13
【问题描述】:
我有以下控制器操作方法,我正在为此方法编写单元测试
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
}
这是我为它编写的单元测试之一,
[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");
}
当我尝试运行测试时,它抛出错误:对象引用未设置为 object 的实例,并且行号显示为 request.querystring,如何在测试方法中设置会话变量,以及任何人都可以建议我检查控制器操作返回类型的正确方法是什么。
【问题讨论】:
标签: c# unit-testing nunit moq