我如何模拟/假在ASP.Net Web表单会话对象? [英] How do I mock/fake the session object in ASP.Net Web forms?

查看:122
本文介绍了我如何模拟/假在ASP.Net Web表单会话对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法创建单元测试时嘲笑/伪造在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的测试替身,因为它是密封。是的,这是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'ers和其他固体practictioners在很大程度上有利于ASP.NET MVC等,更容易测试框架abandonded ASP.NET之一。在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.

您可以采取类似的方法,让你的物品放在一个抽象的会话的工作,然后敷真正HttpSessionState类当你在ASP.NET环境中运行。根据具体情况,你甚至可以重新使用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机组毒鼠强,这依旧可能带有一定的侵入性的动态模拟考试,如的 TypeMock ,althought这些携带大量缺点为好(见<一href=\"http://stackoverflow.com/questions/1718463/what-are-the-real-world-pros-and-cons-of-each-of-the-major-mocking-frameworks/1720654#1720654\">this动态嘲笑比较)。

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表单会话对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆