Java – can the final method be emulated in powermockito in a non final concrete class?

Suppose I have a non - Final concrete class, and the last method is as follows

public class ABC {
  public final String myMethod(){
      return "test test";
  }
}

Can you use powermockito to call myMethod () in JUnit to return something else? thank you

Solution

Do it in this way.

@RunWith(PowerMockRunner.class)
@PrepareForTest(ABC.class)
public class ABCTest {

    @Test
    public void finalCouldBeMock() {
        final ABC abc = powermockito.mock(ABC.class);
        powermockito.when(abc.myMethod()).thenReturn("toto");
        assertEquals("toto",abc.myMethod());
    }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>