public class UserController : Controller
private readonly IUserService _userService;
public UserController(IUserService userService)
_userService = userService;
public IActionResult UserInfo(string userId)
if (string.IsNullOrEmpty(userId))
throw new ArgumentNullException(nameof(userId));
var user = _userService.Get(userId);
return View(user);
测试代码:
[TestMethod()]
public void UserInfoTest()
var userService = new Mock<IUserService>();
userService.Setup(s => s.Get(It.IsAny<string>())).Returns(new User());
var ctrl = new UserController(userService.Object);
//对空参数进行assert
Assert.ThrowsException<ArgumentNullException>(() => {
var result = ctrl.UserInfo(null);
//对空参数进行assert
Assert.ThrowsException<ArgumentNullException>(() => {
var result = ctrl.UserInfo("");
var result = ctrl.UserInfo("1");
Assert.IsNotNull(result);
Assert.IsInstanceOfType(result, typeof(ViewResult));
[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));
//对viewModel进行assert
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);
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);
[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);
public async Task<IActionResult> Login(string password)
if (password == "123")
var claims = new List<Claim>
new Claim("UserName","x")
var authProperties = new AuthenticationProperties
var claimsIdentity = new ClaimsIdentity(
claims, CookieAuthenticationDefaults.AuthenticationScheme);
await HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(claimsIdentity),
authProperties);
return Redirect("login_success");
return Redirect("login_fail");
[TestMethod()]
public async Task LoginTest()
var ctrl = new AccountController();
var authenticationService = new Mock<IAuthenticationService>();
var sp = new Mock<IServiceProvider>();
sp.Setup(s => s.GetService(typeof(IAuthenticationService)))
.Returns(() => {
return authenticationService.Object;
ctrl.ControllerContext = new ControllerContext();
ctrl.ControllerContext.HttpContext = new DefaultHttpContext();
ctrl.ControllerContext.HttpContext.RequestServices = sp.Object;
var result = await ctrl.Login("123");
Assert.IsNotNull(result);
Assert.IsInstanceOfType(result, typeof(RedirectResult));
var rr = result as RedirectResult;
Assert.AreEqual("login_success", rr.Url);
result = await ctrl.Login("1");
Assert.IsNotNull(result);
Assert.IsInstanceOfType(result, typeof(RedirectResult));
rr = result as RedirectResult;
Assert.AreEqual("login_fail", rr.Url);
对HttpContext.AuthenticateAsync进行mock
HttpContext.AuthenticateAsync同样比较常用。这个扩展方法同样是在IAuthenticationService里,所以测试代码跟上面的SignInAsync类似,只是需要对AuthenticateAsync继续mock返回值success or fail。
public async Task<IActionResult> Login()
if ((await HttpContext.AuthenticateAsync()).Succeeded)
return Redirect("/home");
return Redirect("/login");
测试用例:
[TestMethod()]
public async Task LoginTest1()
var authenticationService = new Mock<IAuthenticationService>();
//设置AuthenticateAsync为success
authenticationService.Setup(s => s.AuthenticateAsync(It.IsAny<HttpContext>(), It.IsAny<string>()))
.ReturnsAsync(AuthenticateResult.Success(new AuthenticationTicket(new System.Security.Claims.ClaimsPrincipal(), "")));
var sp = new Mock<IServiceProvider>();
sp.Setup(s => s.GetService(typeof(IAuthenticationService)))
.Returns(() => {
return authenticationService.Object;
var ctrl = new AccountController();
ctrl.ControllerContext = new ControllerContext();
ctrl.ControllerContext.HttpContext = new DefaultHttpContext();
ctrl.ControllerContext.HttpContext.RequestServices = sp.Object;
var act = await ctrl.Login();
Assert.IsNotNull(act);
Assert.IsInstanceOfType(act, typeof(RedirectResult));
var rd = act as RedirectResult;
Assert.AreEqual("/home", rd.Url);
//设置AuthenticateAsync为fail
authenticationService.Setup(s => s.AuthenticateAsync(It.IsAny<HttpContext>(), It.IsAny<string>()))
.ReturnsAsync(AuthenticateResult.Fail(""));
act = await ctrl.Login();
Assert.IsNotNull(act);
Assert.IsInstanceOfType(act, typeof(RedirectResult));
rd = act as RedirectResult;
Assert.AreEqual("/login", rd.Url);
public class MyFilter: ActionFilterAttribute
public override void OnActionExecuting(ActionExecutingContext context)
if (context.HttpContext.Request.Path.Value.Contains("/abc/"))
context.Result = new ContentResult() {
Content = "拒绝访问"
base.OnActionExecuting(context);
[TestMethod()]
public void OnActionExecutingTest()
var filter = new MyFilter();
var actContext = new ActionContext(new DefaultHttpContext(),new RouteData(), new ActionDescriptor());
actContext.HttpContext.Request.Path = "/abc/123";
var listFilters = new List<IFilterMetadata>();
var argDict = new Dictionary<string, object>();
var actExContext = new ActionExecutingContext(
actContext ,
listFilters ,
argDict ,
new AccountController()
filter.OnActionExecuting(actExContext);
Assert.IsNotNull(actExContext.Result);
Assert.IsInstanceOfType(actExContext.Result, typeof(ContentResult));
var cr = actExContext.Result as ContentResult;
Assert.AreEqual("拒绝访问", cr.Content);
actContext = new ActionContext(new DefaultHttpContext(), new RouteData(), new ActionDescriptor());
actContext.HttpContext.Request.Path = "/1/123";
listFilters = new List<IFilterMetadata>();
argDict = new Dictionary<string, object>();
actExContext = new ActionExecutingContext(
actContext,
listFilters,
argDict,
new AccountController()
filter.OnActionExecuting(actExContext);
Assert.IsNull(actExContext.Result);