问题描述
有没有办法在创建单元测试时模拟/伪造 ASP.Net Web 表单中的会话对象?
Is there a way to mock/fake the session object in ASP.Net Web forms when creating unit tests?
我目前将用户详细信息存储在我的业务逻辑访问的会话变量中.
I am currently storing user details in a session variable which is accessed by my business logic.
在单独测试我的业务逻辑时,会话不可用.这似乎表明一个糟糕的设计(虽然我不确定).业务逻辑层应该首先访问会话变量吗?
When testing my business logic in isolation, the session is not available. This seems to indicate a bad design (though I'm not sure). Should the business logic layer be accessing session variables in the first place?
如果是这样,那么我将如何将用户详细信息与假对象交换以进行测试?
If so, then how would I go about swapping the user details with a fake object for testing?
推荐答案
在 ASP.NET 中,您无法创建 HttpSessionState 的 Test Double,因为它是密封
.是的,对于 ASP.NET 的原始设计者来说,这是一个糟糕的设计,但没有太多可做的.
In ASP.NET, you can't create a Test Double of HttpSessionState because it is sealed
. Yes, this is bad design on the part of the original designers of ASP.NET, but there's not a lot to do about it.
这是 TDD 和其他 SOLID 实践者在很大程度上放弃 ASP.NET 转而支持 ASP.NET MVC 和其他更可测试的框架的众多原因之一.在 ASP.NET MVC 中,HTTP 会话由抽象的 HttpSessionStateBase 类建模.
This is one of many reasons why TDD'ers and other SOLID practictioners have largely abandonded ASP.NET in favor of ASP.NET MVC and other, more testable frameworks. In ASP.NET MVC, the HTTP session is modelled by the abstract HttpSessionStateBase class.
您可以采用类似的方法,让您的对象在抽象会话上工作,然后在 ASP.NET 环境中运行时包装真正的 HttpSessionState 类.根据情况,您甚至可以重用 System.Web.Abstractions 中的类型,但如果不能,您可以定义自己的类型.
You could take a similar approach and let your objects work on an abstract session, and then wrap the real HttpSessionState class when you are running in the ASP.NET environment. Depending on circumstances, you may even be able to reuse the types from System.Web.Abstractions, but if not, you can define your own.
无论如何,您的业务逻辑就是您的域模型,它应该独立于任何特定的运行时技术进行建模,所以我认为它不应该访问会话对象第一名.
In any case, your business logic is your Domain Model and it should be modeled independently of any particular run-time technology, so I would say that it shouldn't be accessing the session object in the first place.
如果您绝对需要对涉及 HttpSessionState 的单元 tets 使用 Test Doubles,这仍然可以使用某些侵入性动态模拟,例如 TypeMock 或 Moles,虽然这些带有大量缺点(见 这个动态模拟的比较).
If you absolutely need to use Test Doubles for unit tets involving HttpSessionState, this is still possible with certain invasive dynamic mocks, such as TypeMock or Moles, althought these carry plenty of disadvantages as well (see this comparison of dynamic mocks).
这篇关于如何在 ASP.Net Web 表单中模拟/伪造会话对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!