Mock / Test Superclass in a subclass .. is this possible?

I am looking for a solution for bullying super calls in a subclass of ButtonClicker.

Class Click { public void buttonClick() throws java.lang.Exception { /* compiled code */ } } Class ButtonClicker extends Click { @Override public void buttonClick() throws Exception { super.buttonClick(); } } 
+4
source share
2 answers

Using inheritance reduces the ability to validate your code. Consider replacing the inheritance of delegation and make fun of the delegate.

Remove IClicker Interface

 interface IClicker { void buttonClick(); } 

Add IClicker to the Clicker class. In case you work with third-party code, consider the adapter template

Rewrite ButtonClicker as follows:

 class ButtonClicker implements IClicker { Clicker delegate; ButtonClicker(Clicker delegate) { this.delegate = delegate; } @Override public void buttonClick() throws Exception { delegate.buttonClick(); } } 

Now just pass the layout as a constructor parameter:

 Clicker mock = Mockito.mock(Clicker.class); // stubbing here ButtonClicker buttonClicker = new ButtonClicker(mock); 
+5
source

The answer is no. A layout is just a trivial implementation of an interface. (I mean the interface in the sense of the API, not the specific meaning of the Java keyword). Therefore, he does not know about any implementation details, for example, which class actually implements the functionality (in fact, there is no functionality).

You can create a “spy” on a real object that will allow you to make fun of only some methods, not others, but it also will not allow you to make fun of only a super class method, because the method (s) that you select mock are usually selected by signatures that the same for both the subclass and the superclass.

+3
source

Source: https://habr.com/ru/post/1386338/


All Articles