Search code examples
javaunit-testingjunitmockitopowermockito

How to stub return value for the private method of same class using mockito


I am working on spring based project and writing unit test case using JUnit + Mockito. I am facing a problem while stubbing boolean value to a private method of same test class (after changing access level to public, still I have failed to stub the boolean value).

Below code snippet shows the simulation of same problem

class ABC {

    public String method1(User userObj){
        String result = "";

        if(!isValidUser(userObj.getSessionID())){
            return "InvalidUser";
        } else {
           // execute some logic
        }

        return result;
    }


    private boolean isValidUser(String sessionId) {
        // Here it calls some other class to validate the user 
        if (sessionId == null || UserSessionPool.getInstance().getSessionUser(sessionId) == null) {
            return false;
        } else {
            return true;
        }
    } 
}

Here, I would like to write a test case for method1(). In class ABC I have a method called isValidUser() which helps to identify the user with in a session by looking into a global session pool which holds all logged-in used details i.e. UserSessionPool.getInstance().getSessionUser(sessionId).

While testing method1(), the moment test controller triggers isValidUser(userObj.getSessionID()) I would like to return true from isValidUser() method, so that I can continue to test rest of the implementation logic.

So far I have tried following ways using spy and mocked object to call the isValidUser() method and try to return true but nothing worked well.

Using PowerMockito

PowerMockito.doNothing().when(spyed_ABC_ClassObject, "isValidUser", true);

or

PowerMockito.doReturn(true).when(cntrl, "isValidUser", Mockito.anyString());

Using Whitebox

Whitebox.invokeMethod(spyed_ABC_ClassObject, "isValidUser", Mockito.anyString());

Using Mockito.when

when(spyed_ABC_ClassObject.isValidUser(Mockito.anyString())).thenReturn(true);

or

Mockito.doNothing().when(spyed_ABC_ClassObject).isValidUser(Mockito.anyString());

Solution

  • Can you please try this out.

    @Before
    public void setUp() {
        UserSessionPool mockConnectionPool = Mockito.mock(UserSessionPool.class);
    }
    
    @Test
    public void testName() throws Exception {
        //given
        PowerMockito.mockStatic(UserSessionPool.class);
        BDDMockito.given(UserSessionPool.getInstance()(...)).willReturn(mockConnectionPool);
        Mockito.when(mockConnectionPool.getSessionUser(Mockito.anylong())).thenReturn(something);
    
    
        //then
        PowerMockito.verifyStatic();
    
    }
    

    Hope this helps. Happy coding !