0

How can I mock the "getServerName" method in the superclass using PowerMockito or Mockito?

public class A extends B{

  public static String builder(){
    return new A().get();
  }

  private String get() {
    return this.getServerName();
  }
}

public abstract class B{

  protected String getServerName(){
    return "Server 1";
  }
}

Remembering that I perform by static method:

public static void main (String [] args) {
   String name = A.builder();
}
  • 2
    Possible duplicate of [mocking protected method](https://stackoverflow.com/questions/8312212/mocking-protected-method) – CodeMatrix Jan 21 '19 at 20:13

1 Answers1

0

I was able to solve it!

You have to spy class A

A a = PowerMockito.spy(new A());
PowerMockito.when(a, "getServerName")
           .thenReturn("Mock Value");

// Here is the movement, you have to replace the original constructor.
PowerMockito.whenNew(A.class).withNoArguments().thenReturn(a);

System.out.print(A.builder());

--> Mock Value