How to mock a methods in the same class under test?

435 Views Asked by At

I am using Moq v4.13 and C#. I am trying to test method MethodA on the interface of MyClass : IMyInterface. MethodA has invocations on methods of another interface (IAnother) and I have set up those. These seem to be setup fine.

MethodA also invokes MethodB (also on IMyInterface) and MethodC (public, but not on IMyInterface) in MyClass.

I have set up MethodB but while testing, it seems like actual code of MethodB is invoked.

As for MethodC, I am not sure how to set that up.

public interface MyInterface 
{
    int MethodA();
    int MethodB();
}
public class MyClass : MyInterface 
{
    public MyClass(IAnother b) {...}
    
    public int MethodB(){...}
    public int MethodC(){...}

    public int MethodA()
    {
        ...
        var x = b.MethodX();
        ...
        var a = MethodB();
        ...
        var b = MethodC()

        return a + b + x;
    }
}
public MyInterfaceHarness
{
   Mock<IAnother> _anotherMock;

   public MyInterfaceHarness() 
   {
       _anotherMock = new Mock<IAnother>();
       Mocker = new AutoMocker();
   }

   public AutoMocker Mocker {get;}
   
   public MyClass MethodAHarness()
   {
       Mocker.Use(_anotherMock)  // Mocker is Automocker
       _anotherMock.Setup(m => m.MethodX()).Returns(5); // this seems to be setup fine

      //here I want to setup invocations to MethodB and MethodC
      ....

      Mocker.CreateInstance<MyClass>();
   }
}
[TestFixture]
public MyInterfaceTest 
{
    private  MyInterfaceHarness _harness;
    private AutoMocker _mocker;

    [SetUp]
    public void SetUp()
    {
       _harness = new MyInterfaceHarness();
       _mocker = _harness.Mocker();
    }

    [Test]
    public void Should_Test_MethodA()
    {
        var mi = _harness.MethodAHarness();

        // use _mocker to setup other invocations that need verify            
        ...

        var i = mi.MethodA();
       
       //asserts
       ...
        
    }
}
0

There are 0 best solutions below