如何设置测试方法Moq中查询字符串的值
本文关键字:查询 字符串 Moq 测试方法 何设置 设置 | 更新日期: 2023-09-27 17:49:27
我有以下控制器动作方法,我正在为这个方法写一个单元测试
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");
}
当我试图运行测试时,它抛出错误:对象引用未设置为对象的实例,并且行号显示请求。querystring,如何在测试方法中设置会话变量,谁能告诉我检查控制器动作返回类型的正确方法是什么?
查询字符串
您还需要模拟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);
<<p> 会话/strong> 对于模拟会话,使用上面配置的相同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
然后你可以像使用SetupGet
一样设置值,或者你也可以像
Setup
mockSession.Setup(s => s["token"]).Returns("fooToken")
如果您想要验证会话上是否设置了一个值,您可以在断言代码中添加如下内容:
mockSession.VerifySet(s => s["token"] = "tokenValue", Times.Once);
<<p> ActionResult类型/strong> 我通常做的是使用as
操作符将结果强制转换为所需的类型。如果转换不可能,它将返回null。所以断言可能是这样的:
ViewResult result = controller.Index() as ViewResult;
// Assert
Assert.IsNotNull(result);
Assert.AreEqual("fooView", result.ViewName);
边注
如果您有许多类似的测试,其中代码使用会话和/或查询字符串,那么您需要在每个测试中创建和配置相当多的模拟对象。
您可以向您的测试类添加一个setup方法(它在每次测试之前运行),并将所有构建带有模拟的对象图的代码移到那里。这样,你在每个测试方法上都有一个新的控制器实例,每个测试的安排部分只需要设置模拟的行为和期望。
例如,如果您在测试类中有这样的设置代码: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;
}
每个测试的代码将被简化为如下内容:
[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);
}
这些测试正在测试这个虚拟索引方法
public ActionResult Index()
{
if (Session["token"] == null)
{
if (Request.QueryString["code"] != null)
{
Session["token"] = "tokenValue";
return View("dummy");
}
}
return View();
}