MAK
MAK

Reputation: 2283

How to mock class implementing multiple interfaces and cast the mock object back to the class type?

The Calculator class implements multiple interfaces.

public class Calculator : IAdd, ISubtract, IMultiply, IDivide
{
    ...
}

How would I mock this class, using Moq, and pass is to MyMethod?

public int MyMethod(Calculator calculator)
{
    ...
}

I mocked IMultiply, for instance, and tried to cast it to Calculator but it became null.

Upvotes: 0

Views: 548

Answers (1)

Nkosi
Nkosi

Reputation: 247018

To directly answer the initial question, the Calculator class can be mocked as is

Mock<Calculator> mock = new Mock<Calculator>();

Moq allows for specific derived types to be extracted for setup using As<T>()

Mock<IMultiply> multiplyMock = mock.As<IMultiply>();
multiplyMock.Setup(...);

var subject = new MyClass();

subject.MyMethod(mock.Object);

Design wise I would suggest Calculator start with it's own interface.

Create a single interface to aggregate the functionality

public interface ICalculator: IAdd, ISubtract, IMultiply, IDivide {

}

and have Calculator derive from that

public class Calculator : ICalculator {
    //...
}

The method depend on the abstraction

public int MyMethod(ICalculator calculator) {
    //...
}

And when testing, the interface can be easily mocked as needed.

//Arrange
var calculator = Mock.Of<ICalculator>(); //and configure expected behavior

var subject = new MyClass();

//Act
var result = subject.MyMethod(calculator);

Upvotes: 3

Related Questions