带有 HttpContext 的 ASP.NET MVC 单元测试控制器

编程入门 行业动态 更新时间:2024-10-23 13:33:40
本文介绍了带有 HttpContext 的 ASP.NET MVC 单元测试控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试为我的一个控制器编写单元测试以验证视图是否正确返回,但该控制器有一个访问 HttpContext.Current.Session 的基本控制器.每次我创建控制器的新实例时,都会调用 basecontroller 构造函数,并且测试失败并在 HttpContext.Current.Session 上出现空指针异常.代码如下:

I am trying to write a unit test for my one controller to verify if a view was returned properly, but this controller has a basecontroller that accesses the HttpContext.Current.Session. Everytime I create a new instance of my controller is calls the basecontroller constructor and the test fails with a null pointer exception on the HttpContext.Current.Session. Here is the code:

public class BaseController : Controller { protected BaseController() { ViewData["UserID"] = HttpContext.Current.Session["UserID"]; } } public class IndexController : BaseController { public ActionResult Index() { return View("Index.aspx"); } } [TestMethod] public void Retrieve_IndexTest() { // Arrange const string expectedViewName = "Index"; IndexController controller = new IndexController(); // Act var result = controller.Index() as ViewResult; // Assert Assert.IsNotNull(result, "Should have returned a ViewResult"); Assert.AreEqual(expectedViewName, result.ViewName, "View name should have been {0}", expectedViewName); }

关于如何模拟(使用 Moq)在基本控制器中访问的会话以便在后代控制器中运行测试的任何想法?

Any ideas on how to mock (using Moq) the Session that is accessed in the base controller so the test in the descendant controller will run?

推荐答案

如果您正在使用 Typemock,您可以这样做:

If you are using Typemock, you can do this:

Isolate.WhenCalled(()=>controller.HttpContext.Current.Session["UserID"]) .WillReturn("your id");

测试代码如下:

[TestMethod] public void Retrieve_IndexTest() { // Arrange const string expectedViewName = "Index"; IndexController controller = new IndexController(); Isolate.WhenCalled(()=>controller.HttpContext.Current.Session["UserID"]) .WillReturn("your id"); // Act var result = controller.Index() as ViewResult; // Assert Assert.IsNotNull(result, "Should have returned a ViewResult"); Assert.AreEqual(expectedViewName, result.ViewName, "View name should have been {0}", expectedViewName); }

更多推荐

带有 HttpContext 的 ASP.NET MVC 单元测试控制器

本文发布于:2023-11-14 13:47:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1587382.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:控制器   单元测试   ASP   HttpContext   MVC

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!