对ViewData进行测试
我们编写Action的时候还会涉及ViewData给视图传递数据,这部分同样需要测试。修改Action代码,对ViewData进行赋值:
public IActionResult UserInfo(string userId)
{
if (string.IsNullOrEmpty(userId))
{
throw new ArgumentNullException(nameof(userId));
}
var user = _userService.Get(userId);
ViewData["title"] = "user_info";
return View(user);
}
修改测试用例,加入对ViewData的测试代码:
[TestMethod()]
public void UserInfoTest()
{
var userService = new Mock<IUserService>();
userService.Setup(s => s.Get(It.IsAny<string>())).Returns(new User()
{
Id = "x"
}) ;
var ctrl = new UserController(userService.Object);
Assert.ThrowsException<ArgumentNullException>(() => {
var result = ctrl.UserInfo(null);
});
Assert.ThrowsException<ArgumentNullException>(() => {
var result = ctrl.UserInfo("");
});
var result = ctrl.UserInfo("1");
Assert.IsNotNull(result);
Assert.IsInstanceOfType(result, typeof(ViewResult));
var vr = result as ViewResult;
Assert.IsNotNull(vr.Model);
Assert.IsInstanceOfType(vr.Model, typeof(User));
var user = vr.Model as User;
Assert.AreEqual("x", user.Id);
//对viewData进行assert
Assert.IsTrue(vr.ViewData.ContainsKey("title"));
var title = vr.ViewData["title"];
Assert.AreEqual("user_info", title);
}
对ViewBag进行测试
因为ViewBag事实上是ViewData的dynamic类型的包装,所以Action代码不用改,可以直接对ViewBag进行测试:
[TestMethod()]
public void UserInfoTest()
{
var userService = new Mock<IUserService>();
userService.Setup(s => s.Get(It.IsAny<string>())).Returns(new User()
{
Id = "x"
}) ;
var ctrl = new UserController(userService.Object);
Assert.ThrowsException<ArgumentNullException>(() => {
var result = ctrl.UserInfo(null);
});
Assert.ThrowsException<ArgumentNullException>(() => {
var result = ctrl.UserInfo("");
});
var result = ctrl.UserInfo("1");
Assert.IsNotNull(result);
Assert.IsInstanceOfType(result, typeof(ViewResult));
var vr = result as ViewResult;
Assert.IsNotNull(vr.Model);
Assert.IsInstanceOfType(vr.Model, typeof(User));
var user = vr.Model as User;
Assert.AreEqual("x", user.Id);
Assert.IsTrue(vr.ViewData.ContainsKey("title"));
var title = vr.ViewData["title"];
Assert.AreEqual("user_info", title);
//对viewBag进行assert
string title1 = ctrl.ViewBag.title;
Assert.AreEqual("user_info", title1);
}
设置HttpContext
我们编写Action的时候很多时候需要调用基类里的HttpContext,比如获取Request对象,获取Path,获取Headers等等,所以有的时候需要自己实例化HttpContext以进行测试。








