Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock/Test Super class call in subclass..is it possible?

I am looking for a solution to mock the super call in subclass ButtonClicker.

Class Click {
      public void buttonClick() throws java.lang.Exception { /* compiled code */ }     } 

Class ButtonClicker extends Click { 
    @Override
    public void buttonClick() throws Exception {

        super.buttonClick();
    } }
like image 338
Himalay Majumdar Avatar asked Jan 18 '23 01:01

Himalay Majumdar


1 Answers

Using inheritance reduces testability of your code. Consider replacing inheritance with the delegation and mock the delegate.

Extract the interface IClicker

interface IClicker {
    void buttonClick();
}

Implement IClicker in Clicker class. In case that you are working with third-party code consider using Adapter Pattern

Rewrite your ButtonClicker as following:

class ButtonClicker implements IClicker {
    Clicker delegate;

    ButtonClicker(Clicker delegate) {
        this.delegate = delegate;
    }

    @Override
    public void buttonClick() throws Exception {
        delegate.buttonClick();
    }

}

Now just pass the mock as a constructor parameter:

Clicker mock = Mockito.mock(Clicker.class);
// stubbing here
ButtonClicker buttonClicker = new ButtonClicker(mock);
like image 105
Mairbek Khadikov Avatar answered Jan 27 '23 22:01

Mairbek Khadikov