I'm having trouble stubbing a final method, which is used inside of a class I'm trying to test. The problematic line in my test class is here:
PowerMockito.when(connectionMock.authUser("fake-user", "fake-password")).thenReturn("random string");
which throws a NullPointerException. My test class looks like this:
@RunWith(PowerMockRunner.class)
@PrepareForTest({MyClass.class, APIClientConnection.class})
public class MyClassTest {
@Test
public void apiConnect() throws Exception {
MyClass c = new MyClass();
APIClientConnection connectionMock = PowerMockito.mock(APIClientConnection.class);
PowerMockito.whenNew(APIClientConnection.class).withAnyArguments().thenReturn(connectionMock);
PowerMockito.when(connectionMock.authUser("fake-user", "fake-password")).thenReturn("random string");
c.apiConnect("fake-host", 80, "fake-user", "fake-password");
}
}
The class I'm testing is as follows:
public class MyClass {
public MyClass() { }
public APIClientConnection apiConnect(String host, int port, String user, String pass) {
conn = new APIClientConnection(host, port);
conn.authUser(user, pass);
}
}
Where authUser() is defined final like so:
public class APIClientConnection {
public final String authUser(String username, String password) {
...
}
}
I'm following along with How to mock non static methods using PowerMock and Can Powermockito mock final method in non-final concrete class?. I've tried some variations such as using Mockito instead of PowerMock to stub authUser, and adding APIClientConnection.class to the PrepareForTest annotation. I can't figure out why it isn't working though. What am I doing wrong?