lundi 26 octobre 2015

Moq a class that has an internal property and which implements an interface

So I have a class which both implements an interface and has an internal property. I need to mock both of these using Moq to test a method.

public interface IMyObject
{
    bool myMethod (String input);
}

public class MyObject : IMyObject
{
    public bool myMethod(String input) {...}
    internal bool myProperty {get;}
}

Now, I can mock either using Moq.

myMethod:

var myIObjectMock = mockRepository.Create<IMyObject>();
myIObjectMock.Setup(m => m.myMehtod(It.IsAny<String>())).Returns((String input) => {...});

myProperty:

var myObjectMock = mockRepository.Create<MyObject>();
myObjectMock.SetupGet(m => m.myProperty).Returns(...);

My question is, how do I mock both?

The core of the problem seems to be that I'm mocking an interface in the first case and a class in the second. So the solution I see is to make it so you can mock the property and the method by mocking either the class or the interface. This would mean either switching the internal property into a public property and put it as part of the interface or making the method virtual.

Is there a solution that does not involve changing the MyObject class?

Aucun commentaire:

Enregistrer un commentaire