mat
mat

Reputation: 1717

Mocking a method with different signatures where one has Object as a parameter type

I have the following interfaces

public interface IInfo
{
    bool IsCompatibleWith (Object informationObject);
}

public interface IInfo<T> : IInfo
{
    bool IsCompatibleWith (T informationObject);
}

and try to do the following Mocks

Foo f = new Foo();
Mock<IInfo<Foo>> infoMock = new Mock<IInfo<Foo>>();
infoMock.Setup(i => i.IsCompatibleWith(f)).Returns(true);

The test is then running the following lines

IInfo mockedInfo;
mockedInfo.IsCompatibleWith(f);

The problem is, that the Setup method sets up the IsCompatibleWith (T informationObject), while the code is calling the IsCompatibleWith (Object informationObject) one. How can I setup both signatures?

Upvotes: 4

Views: 889

Answers (1)

Old Fox
Old Fox

Reputation: 8725

The following snippet shows the way to configure both methods:

//configure the method with the `object` as a parameter
infoMock.Setup(i => i.IsCompatibleWith((object)f)).Returns(true);

//configure the method with the `IModel` as a parameter
infoMock.Setup(i => i.IsCompatibleWith(f)).Returns(true);

Moq records the arguments as is. When you cast your instance to object, the method bool IsCompatibleWith(Object informationObject) will accept the registration

Upvotes: 7

Related Questions