Search code examples
junitmockitopowermockpowermockito

why Mock object has doreturn and thenreturn for mock?


Note: I understand that in spy we can differenciate among these two. I went all over internet but I still some doubts on doreturn/when and when/thenreturn in Mockito .Below is my doubt,

1)Are doreturn/when and when/thenreturn acts same for mock object ? i.e: its does not matter whether you call doreturn/when or when/thenreturn for a mock object it will not call real method , but a stubbed call. is my understanding is correct on this ?

2)doreturn/when and when/thenreturn makes a difference only for spy objects in Mockito. i.e doreturn/when - will not call real methos and when/thenreturn will call real method.Is my understanding correct on this ?

If my understanding on above 2 points are correct then we should always use doreturn/when so that we dont need to learn 2 syntax ,Right ?


Solution

  • After doing by my own I came to know that:

    1. doreturn/when and when/thenreturn are same for mocked object. None of them call the actual method
    2. doreturn/when and when/thenreturn have different behaviour for spied object. doreturn/when - it will not call real method on spied object when/thenreturn - it will call real method on spied object

    Hope it helps!