MVC vb.net项目的单元测试。我的控制器中的一个操作方法,我在Request.Params["FieldName"]
在这种情况下,如何在单元测试方法中模拟:Request.Params["FieldName"]
?喜欢VB.net,也接受c#。
Dim httpRequest = New Mock(Of System.Web.HttpRequestBase)()
Dim httpContext = New Mock(Of System.Web.HttpContextBase)()
Dim parameters As New NameValueCollection()
parameters("YourField") = "testField"
httpRequest.Setup(Function(x) x.Params).Returns(parameters)
httpContext.Setup(Function(x) x.Request).Returns(httpRequest.[Object])
答案 0 :(得分:0)
您需要模拟请求和上下文。在请求中,您还需要模拟if (mysqli_num_rows($results) == 1)
{
$_SESSION['username'] = $username;
$_SESSION['success'] = "Du er nå logget inn";
$details = $results->fetch_array(MYSQLI_ASSOC)
if( $details['admin'] == '1')
{
redirect him to admin here
// header('location: index.php');
}
else if($details['admin'] == '0')
{
redirect him to normal page
//header('location: index.php');
}
}
,但问题是此索引器不是Params["YourField"]
,因此您将无法模拟它。相反,你可以模拟virtual
方法。以下是使用Moq:
Get
在您的代码中,您需要使用var request = new Mock<HttpRequestBase>();
// We are mocking the Get method
request.Setup(x => x.Params.Get("FieldName")).Returns("whatever...");
var context = new Mock<HttpContextBase>();
context.Setup(x => x.Request).Returns(request.Object);
而不是索引器(您不能使用Get
)。