J
J
Java Testing Notes
Ask or search…
K
Comment on page

PowerMockito.suppress()

suppress() is one of the most powerful API's provided by PowerMock.
With suppress() you can manipulate bytecode to skip executing any method or constructor.
For example, lets say you had an class which extended an library or code that you don't own, you can suppress its constructor.
// Example Source Class
public class ExampleClass extends CustomLibClass {
public ExampleClass() {
System.out.println("class initialised");
}
public void someMethod() {
super.someMethod();
}
}
Here, our source class extends CustomLibClass which we do not need to test. But creating a object of ExampleClass will also call constructor of CustomLibClass. This can be avoided if we tell Powermock to suppress constructor of CustomLibClass.
// Test of Example Source Class
@RunWith(PowerMockRunner.class)
@PrepareForTest({
ExampleClass.class
})
public class ExampleClassTest {
private ExampleClass classUnderTest;
@Before
public void setUp() throws Exception {
// We should suppress constructor of CustomLibClass
// There are multiple ways to do that
// 1. Suppress with matching constructor, in below case it will only suppress constructor without any parameter
PowerMockito.suppress(MemberMatcher.constructor(CustomLibClass.class));
// Or using Java Reflection
PowerMockito.suppress(CustomLibClass.class.getConstructor());
// 2. Suppress all declared constructor
PowerMockito.suppress(MemberMatcher.constructorsDeclaredIn(CustomLibClass.class));
// Or Using Java Reflection API's
PowerMockito.suppress(CustomLibClass.class.getConstructors());
// Create constructor of ExampleClass, it will not call constructor of CustomLibClass
classUnderTest = new ExampleClass();
}
@Test
public void someMethod_shouldDoNothing() {
// This is just an example, it is not necessary for an example test to test something :D
PowerMockito.suppress(CustomLibClass.class.getDeclaredMethod("someMethod"));
}
}
Note: keep in mind, if you need to manipulate behavior (byte code) of any class, as we are doing in case of suppress constructor, we need to add ExampleClass.class in @PrepareForTest.