[英]Substitute a sealed class
I have a class A
that expose a HttpRequestHeaders
as a property. 我有一个
A
类,它将HttpRequestHeaders
作为属性公开。 The class under test is B
. 被测试的班级是
B
B
is using A
. B
正在使用A
A
is also a fake class that is used only for unit test. A
也是一个仅用于单元测试的假类。 A
inherit an interface that impose the definition of the HttpRequestHeaders
property. A
继承那些强加的定义的接口HttpRequestHeaders
财产。 So I need to substitute the HttpRequestHeaders
so that I can test B
Unfortunately HttpRequestHeaders
is a sealed class thus it can not be substitute by NSubstitute: 所以我需要替换
HttpRequestHeaders
以便我可以测试B
不幸的是HttpRequestHeaders
是一个密封的类因此它不能被NSubstitute替代:
Could not load type 'Castle.Proxies.HttpRequestHeadersProxy_2' from assembly 'DynamicProxyGenAssembly2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=a621a9e7e5c32e69' because the parent type is sealed.
无法从程序集“DynamicProxyGenAssembly2,Version = 0.0.0.0,Culture = neutral,PublicKeyToken = a621a9e7e5c32e69”加载类型“Castle.Proxies.HttpRequestHeadersProxy_2”,因为父类型已被密封。
What would be the general solution to overcome this situation? 克服这种情况的一般解决方案是什么?
Instead of trying to find a way to fake a sealed
object, I'd instead look to see if I can get a real instance of one, assuming it doesn't have too many dependencies. 我没有试图找到一种伪造
sealed
对象的方法,而是想看看我是否能得到一个真实的实例,假设它没有太多的依赖关系。
On the plus side, HttpRequestHeaders
doesn't have too many dependencies. 从
HttpRequestHeaders
方面来说, HttpRequestHeaders
没有太多依赖项。 On the down side, it only has an internal
constructor. 在不利方面,它只有一个
internal
构造函数。 Happily, though, HttpRequestMessage
can be freely constructed and exposes a Headers
property which will perform the required construction for you. 但令人高兴的是,
HttpRequestMessage
可以自由构建并公开一个Headers
属性,它将为您执行所需的构造。
Alternatively, you might consider using reflection to create the object despite it only having the internal
constructor - it's pick your poison time - create an unneeded, disposable object to cleanly create the headers, or start using reflection. 或者,您可以考虑使用反射创建对象,尽管它只有
internal
构造函数 - 它会选择您的毒药时间 - 创建一个不需要的一次性对象来干净地创建标题,或者开始使用反射。
Depending on the version of Visual Studio you're using, try Fakes ( http://msdn.microsoft.com/en-us/library/hh549175.aspx ) 根据您使用的Visual Studio版本,请尝试Fakes( http://msdn.microsoft.com/en-us/library/hh549175.aspx )
This is especially useful if you don't have control over the dependencies. 如果您无法控制依赖项,则此功能尤其有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.