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() {

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
public class ExampleClassTest {

    private ExampleClass classUnderTest;

    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
        // Or using Java Reflection
        // 2. Suppress all declared constructor
        // Or Using Java Reflection API's

        // Create constructor of ExampleClass, it will not call constructor of CustomLibClass
        classUnderTest = new ExampleClass();

    public void someMethod_shouldDoNothing() {
        // This is just an example, it is not necessary for an example test to test something :D

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.

Last updated