Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Substitute a sealed class

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?

like image 851
mathk Avatar asked Sep 02 '25 17:09

mathk


1 Answers

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.

like image 80
Damien_The_Unbeliever Avatar answered Sep 05 '25 06:09

Damien_The_Unbeliever



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!