Search code examples
javaspringjunitmockitopowermockito

Can any one explain in which case we use PowerMockito.when() and PowerMockito.doReturn()


I was writing test case for my service class but i m not sure when to use PowerMockito.when() and PowerMockito.doReturn() as both behavior looks similar to me.


Solution

  • From my understanding doReturn() and when() are almost equal ,but the difference which i found in when() type-checking of the value that you're returning at compile time where as in doReturn() there is no type-checking of the value that you're returning at compile time

    For Example:

    case1:

    PowerMockito.when(mongoTamplate.getCollection(Mockito.eq("testdoc"))).thenReturn(mongoCollection);
    

    case2:

    powerMockito.doReturn(mongoCollection).when(mongoTamplate).getCollection(Mockito.eq("test-doc"))
    

    In case 1 type of mongoCollection is checked at compile time where as in case2 type of mongoCollection is not checked at compilation