Question

I have a class A that expose a HttpRequestHeaders as a property. The class under test is B.

  • B is using A.
  • A is also a fake class that is used only for unit test.
  • A inherit an interface that impose the definition of the HttpRequestHeaders property.

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:

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.

What would be the general solution to overcome this situation?

Was it helpful?

Solution

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.

On the plus side, HttpRequestHeaders doesn't have too many dependencies. On the down side, it only has an internal constructor. Happily, though, HttpRequestMessage can be freely constructed and exposes a Headers property which will perform the required construction for you.

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.

OTHER TIPS

Depending on the version of Visual Studio you're using, try Fakes (http://msdn.microsoft.com/en-us/library/hh549175.aspx)

This is especially useful if you don't have control over the dependencies.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top