jeudi 7 mai 2015

PowerMock complains of incorrect arguments even though the private method is mocked

I was trying out PowerMock, and am trying to mock a private method like so:

expectPrivate(nodeAccessor, "doLogin", anyString(), anyString()).andReturn(true);

That is, I want true to be returned from doLogin irrespective of the parameters passed. The public method which delegates to this private method simply passes-on the arguments. Here is the definition of the class to be mocked:

class N {
        public boolean login(String username, String password) {
            return doLogin(username, password);
        }
        private boolean doLogin(String u, String p){
            //validate login
            //...
            //...
            return true;
        }
     }

And this is how I am trying to invoke the mock:

@Test
public void testMockLogin() throws Exception {
    // mocking only specific methods
    N n = createPartialMock(N.class,
            "doLogin", String.class, String.class);
    boolean expected = true;
    expectPrivate(n, "doLogin", anyString(), anyString()).andReturn(expected);
    replay(n);
    boolean actual = n.login("A", "B"); // <--!! problem !!
    //boolean actual = n.login(anyString(), anyString()); // <-- no problem!
    verify(n);
    assertEquals("Expected and actual did not match", expected, actual);
}

So the mocking framework is not happy when specific Strings are passed to the public login() method, but fine when anyString is used. Ideally, I would expect that since the call to the private doLogin is mocked, this should not be the case. What am I missing?

Aucun commentaire:

Enregistrer un commentaire