Mocking a base class method call with Moq

后端 未结 6 1795
不思量自难忘°
不思量自难忘° 2020-12-06 16:12

I am modifiying a class method which formats some input paramater dates which are subsequently used as params in a method call into the base class (which lives in another as

6条回答
  •  心在旅途
    2020-12-06 16:35

    It is quite possible mocking base class. But you will have to modify target class.

    For ex. DerivedClass extends BaseClass. BaseClass has methods MethodA(), MethodB(), MethodC()... The DerivedClass has this method:

    void MyMethod() {
      this.MethodA();
      this.MethodB();
      this.MethodC();
    }
    

    You want to mock base class in order to validate that all MethodA(), MethodB(), MethodC() are being called inside MyMethod().

    You have to create a field in the DerivedClass:

    class DerivedClass {
      private BaseClass self = this;
      ...
    }
    

    And also You have to modify the MyMethod():

    void MyMethod() {
      self.MethodA();
      self.MethodB();
      self.MethodC();
    }
    

    Also add a method, which can inject the this.self field with Mock object

    public void setMock(BaseClass mock) {
      this.self = mock;
    }
    

    Now you can mock:

    DerivedClass target = new DerivedClass ();
    BaseClass  mock = new  Mock(typeof(BaseClass));
    target.setMock(mock);
    target.MyMethod();
    
    mock.verify(MethodA);
    mock.verify(MethodB);
    mock.verify(MethodC);
    

    Using this technic, you can also mock nested method calls.

提交回复
热议问题