MakePeaceGreatAgain
MakePeaceGreatAgain

Reputation: 37050

mock class with internal constructor

I have some class that I want to mock and that has only an internal expecting some arguments. Therefor I added the InternalsVisibleTo-attribute to my system under test and wrote the following code:

var target = Substitute.For<MyClass>(testArgs);

where MyClass is this:

public class MyClass
{
    internal MyClass(int i) { ... }
}

When debugging I get a NotSupporetedException because I don´t have a default-constructor. However as I have an internal one (which is visible to my test-assembly because of InternalsVisibleTo) I´d expect that one to be used instead.

Of course I could just make the constructor public but this would allow any user of my API to create instances of MyClass which I´d like to avoid. Is there anything I missed to get this to work?

Upvotes: 1

Views: 1654

Answers (1)

MakePeaceGreatAgain
MakePeaceGreatAgain

Reputation: 37050

We don´t have to expose the class´ constructor to the API, all we have to do is make the constructor internal protected to make it visible to classes deriving from MyClass or classes within the assembly where MyClass is located. Thus NSubstitute is able to create a class that derives from MyClass and redirects the constructor-call to the base-constructor.

Upvotes: 0

Related Questions