该控制器不可测试吗?

时间:2018-11-09 10:58:15

标签: .net unit-testing

在当前状态下,由于对用户身份验证(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);
}

1 个答案:

答案 0 :(得分:1)

您可以将IHttpContextAccessor注入控制器,并使用_httpContext.GetRouteData()_httpContext.User使其可测试。

阅读本文以了解要测试的内容以及如何编写可测试的代码-https://www.toptal.com/qa/how-to-write-testable-code-and-why-it-matters