Logo Questions Linux Laravel Mysql Ubuntu Git Menu

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;

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?

like image 689
mat Avatar asked Mar 16 '23 10:03


1 Answers

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

like image 76
Old Fox Avatar answered Apr 26 '23 06:04

Old Fox