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.
With
NSubstitute
it is quite easy. First create a mock for your interface:Now you can mock the member by setting any return-type for the property:
Finally provide that mocked instance as parameter to the service depending on that instance, for example:
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 theReturns
-statement. Just have a look at http://nsubstitute.github.io/help/set-return-value for further information.