Setting a readonly property of a class for unit testing

9.5k views Asked by At

I have an interface like this

public interface IConnection
{
    Strategy Gc { get; }

    bool IsConnected();

    bool Connect();
}

I want to unit test methods of a class that uses this interface. Now I want to set Gc but it happens to be readonly. Is there a way to set Gc field without making changes to this interface class? I am using MS fakes and Nsubstitute for unit testing. However, apparently none provides a solution. PrivateObject does not work either.

Changing Interface is not an option. Suggest better solutions.

1

There are 1 answers

1
MakePeaceGreatAgain On BEST ANSWER

With NSubstituteit is quite easy. First create a mock for your interface:

var mock = Substitute.For<IConnection>();

Now you can mock the member by setting any return-type for the property:

mock.Gc.Returns(Substitute.For<Strategy>());

Finally provide that mocked instance as parameter to the service depending on that instance, for example:

var target = new MyClassToTest();
target.DoSomething(mock);  // mock is an instance of IConnection

Now whenever your method is called it returns a dumm-instance for Strategy. Of course you can also set any other arbitrary return-type within the Returns-statement. Just have a look at http://nsubstitute.github.io/help/set-return-value for further information.