我有一个单元测试夹具,我正在尝试在ASP.NET MVC控制器上测试一个ControllerAction,该控制器用于Web应用程序上的成员函数.我正在尝试模拟测试的HttpContext.正在测试的ControllerAction实际上设置了HttpContext的属性,例如Session值,Response.Cookies值等.这不是所有代码,但这里是我试图运行的测试的粗略示例:
[Test]
public void ValidRegistrationDataSuccessfullyCreatesAndRegistersUser()
{
var context = new Mock<HttpContextBase>() {DefaultValue = DefaultValue.Mock};
context.SetupAllProperties();
var provider = new Mock<MembershipProvider>(new object[] {context.Object});
var controller = new AccountController(context.Object, provider.Object);
// This just sets up a local FormCollection object with valid user data
// in it to use to attempt the registration
InitializeValidFormData();
ActionResult result = controller.Register(_registrationData);
Assert.IsInstanceOfType(typeof(ViewResult), result);
// Here is where I'd like to attempt to do Assertions against properties
// of the HttpContext, like ensuring that a Session …Run Code Online (Sandbox Code Playgroud) 我是mvc4和TDD的新手.
当我尝试运行此测试时,它失败了,我不知道为什么.我已经尝试了很多东西,我开始在圈子里跑来跑去.
// GET api/User/5
[HttpGet]
public HttpResponseMessage GetUserById (int id)
{
var user = db.Users.Find(id);
if (user == null)
{
//return Request.CreateResponse(HttpStatusCode.NotFound);
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
}
return Request.CreateResponse(HttpStatusCode.OK, user);
}
[TestMethod]
public void GetUserById()
{
//Arrange
UserController ctrl = new UserController();
//Act
var result = ctrl.GetUserById(1337);
//Assert
Assert.IsNotNull(result);
Assert.AreEqual(HttpStatusCode.NotFound,result.StatusCode);
}
Run Code Online (Sandbox Code Playgroud)
结果如下:
Test method Project.Tests.Controllers.UserControllerTest.GetUserById threw exception:
System.ArgumentNullException: Value cannot be null. Parameter name: request
Run Code Online (Sandbox Code Playgroud) 我尝试对单元测试返回的方法:
return Json(new { ok = true, newurl = Url.Action("Index") });
Run Code Online (Sandbox Code Playgroud)
但是这一行抛出NullReferenceException是由这部分收益引起的:
newurl = Url.Action("Index")
Run Code Online (Sandbox Code Playgroud)
我试图做一些事情:
Request.SetupGet(x => x.Url).Returns(// Data here);
Run Code Online (Sandbox Code Playgroud)
没有任何影响。
你能建议我任何解决方案吗?