Sometimes when I write unit tests I should to mock reference to superclass.
I have read this question: question
This answer answer with DI advice to refactor code. But I cannot it
this answer another answer is not suitable if superclass method is enough big. In my case I have very big code. Yes I know that it is brokes SOLID OOD principes but I just should to write test. I have not enough time for refactor.
said question was asked 4 years ago!
Does currently Mockito or Powermock can resolve this issue ?
code example:
class BaseService {
public void save() {
// a lot of code here! I cannot change this code.
}
}
public Childservice extends BaseService {
public void save(){
//logic for testing
super.save();
//logic for testing
}
}
public class Parent {
public int save() {
return 99;
}
}
public class Child extends Parent {
public int save() {
int i = super.save();
return i*2;
}
}
and test:
@RunWith(PowerMockRunner.class)
@PrepareForTest(Parent.class)
public class ParentTest {
@Test
public void testSave() {
PowerMockito.suppress(PowerMockito.methodsDeclaredIn(Parent.class));
System.out.println(new Child().save());
}
}
output: 198
Subclass methods can call superclass methods if both methods have the same name. From the subclass, reference the method name and superclass name with the @ symbol.
Starting with Mockito version 3.5. 0, we can now mock Java constructors with Mockito. This allows us to return a mock from every object construction for testing purposes.
Mockito 's doNothing() is used when you want to test void methods because void methods do not return anything so there is no way you can verify using assert. These void methods may be anywhere, for example, in service class, in dao class, etc.
With Powermock you can replace or suppress methods, so it is possible to change the action done by BaseService.save()
. You can also make methods to do nothing with suppressing. You can even suppress static initializer blocks.
Please read this blog entry of the Powermock authors. See chapter "Replacing".
UPDATE:
Suppress seems to work for me, but replace not. See the picture below:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With