Search code examples
javamockitopowermockito

How to mock objects of external libraries?


I have the following method that I want to test:

    public String createUser(Keycloak keycloak) {
        final Response response = keycloak.realm(this.realm).users().create(this.toUserRepresentation());
        String userId = response.getLocation().getPath().replaceAll(".*/([^/]+)$", "$1");
        return userId;
    }

I have tried with this but the getPath() always return an empty string.

@PrepareForTest(URI.class)
@RunWith(PowerMockRunner.class)
class UserTest {

    @Mock(answer = Answers.RETURNS_DEEP_STUBS)
    private Keycloak keycloak;

    @Mock
    private Response response;

    @Test
    public void createUserTest() throws Exception {
        URI uri = PowerMockito.mock(URI.class);

        when(uri.getPath()).thenReturn("https://myserver/myid[\r][\n]");
        when(response.getLocation()).thenReturn(uri);
        when(keycloak.realm(any()).users().create(any())).thenReturn(response);


        assertEquals("myid", user.createUser(keycloak));
    }

}

How should I mock the URI.getPath() called so that it returns the expected value?


Solution

  • You probably need to include the class under test in the @PrepareForTest annotation. For example:

    @PrepareForTest({URI.class, User.class})
    

    Then uri.getPath() will return a non-empty value.


    Please notice that you test URI will never evaluate to just "myid", it will also include "[\r][\n]".

    ("https://myserver/myid[\r][\n]").replaceAll(".*/([^/]+)$", "$1")