Share via


Construct class with internal constructor

Question

Friday, June 13, 2008 9:11 AM | 1 vote

Hi,

This question might seem strange, but I should explain I'm attempting to unit test my code.  As part of that, I'd like to simulate as many of the conditions that could be present as possible.

I'm using a library that does some networking, and one of its method may throw three exceptions.  What I want to do is use mocking to simulate each exception being thrown (and correctly handled), but unfortunately one of the exception classes has been defined with only internal constructors, so I can't create an instance of it.

Is there any way I can construct an instance using reflection?

Cheers,
Adam

All replies (3)

Friday, June 13, 2008 1:18 PM âś…Answered | 3 votes

Hi Adam,

you certainly can. Here's some code:

// Fetch the non-public instance constructors from the wanted exception type. 
ConstructorInfo[] constructors =  
    typeof(MyInternalException).GetConstructors( 
    BindingFlags.NonPublic | BindingFlags.Instance); 
 
// I expect there is only one constructor, and I invoke it, and cast the object. 
Exception myException = (Exception)constructors[0].Invoke(null); 
 
// We throw the created exception. 
throw myException; 

I hope this helps.


Friday, June 13, 2008 1:28 PM | 1 vote

Hi Adam,

  when you want to have accessible internal classes and methods in other assembly then apply InternalsVisibleToAttribute to the assembly where are internals classes. See: http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute.aspx

Petr


Friday, June 13, 2008 2:03 PM

NET Junkie - thanks a lot, that worked perfectly.  I knew I had to do something like that, just didn't have a chance to get it working.  Thanks again.

Petr - unfortunately I have no control over the library that has the internals, but thanks for the tip.

Cheers,
Adam