Home > Software design >  How do you mock a method in a sub class?
How do you mock a method in a sub class?

Time:11-09

How do you mock a sub class and it’s methods using moq?

Below is the example:

Public class A
{
   Private IClassB _b;

   Public A(IClassB b)
   {
     _b = b
   }

   Public void Main()
   {
      //I need to mock the method on C.
      _b.C.HowDoIMockThisMethod();
   }
}

Mocking B is no problem but it’s C and the method it’s calling which is what I cannot figure out.

Any help is most appreciated!

CodePudding user response:

If 'C' is a property of B you need to mock a return type, e.g.


Mock<IClassB> mockOfB = new Mock<IClassB>();
var testee = new A(mockOfB.Object);

mockOfB.SetupGet(x => x.C).Returns(Mock.Of<IClassC>()); // Or a separately generated instance

testee.Main();

CodePudding user response:

For the purposes of demonstrating that the functionality exists assuming

public interface IClassB {
    IClassC  C { get; set; }
}

public interface IClassC {
    int HowDoIMockThisMethod();
}

Moq allows for auto mocking hierarchies otherwise known as recursive mocks

[TestClass]
public class RecursiveMocksTests {
    [TestMethod]
    public void C_Should_Recursive_Mock() {
        //Arrange
        int expected = 5;
        Mock<IClassB> mockOfB = new Mock<IClassB>();
        // auto-mocking hierarchies (a.k.a. recursive mocks)
        mock.Setup(_ => _.C.HowDoIMockThisMethod()).Returns(expected);

        var subject = new A(mockOfB.Object);

        //Act
        subject.Main();

        //Assert
        //...
    }
}

Note that at no point was IClassC ever initialized or configured. The framework will auto mock that interface because of the setup shown above.

If however, more functionality is needed from an IClassC, then a proper mock should be done and configured accordingly.

Reference Moq Quickstart: Properties

  • Related