在当前状态下,由于对用户身份验证(user.identity)和路由数据(RouteData.Values)的依赖性,我认为我无法对其进行测试计划是检查它是否正在返回视图。我应该尝试模拟/伪造这些值,还是不首先测试像这样的控制器?
public IActionResult Index()
{
BlogHomeVM vm = new BlogHomeVM();
int skip = int.TryParse((string)this.RouteData.Values["skip"], out skip) ? skip : 0;
int showPosts = 3;
vm.PageTitle = "Async and wait";
vm.totalPosts = _context.Posts.Where(y => y.PublishedFrom <= DateTime.Now).Count();
vm.Posts = _context.Posts
.Where(y => y.PublishedFrom <= DateTime.Now || User.Identity.IsAuthenticated)
.OrderByDescending(x => x.DatePublished)
.Skip(skip)
.Take(showPosts)
.ToList();
vm.AllCats = _context.PostCategory.ToList();
vm.PageName = "Blog";
vm.skip = skip;
vm.showPosts = showPosts;
return View(vm);
}
答案 0 :(得分:1)
您可以将IHttpContextAccessor
注入控制器,并使用_httpContext.GetRouteData()
和_httpContext.User
使其可测试。
阅读本文以了解要测试的内容以及如何编写可测试的代码-https://www.toptal.com/qa/how-to-write-testable-code-and-why-it-matters