2

I want to use mockito and stub a method. I want method to return different values basing on stubbing. But it always returns the first output. Below is how is my setup

Class Controller{    //this is singleton class

private final Foo foo=AFacftory.getFoo();    //this variable is initialized only once for the whole life cycle

//Some code below that I want to test is here
foo.functionInFoo()



}

    Class Foo{
    int functionInFoo(){

    }
}

Test1
Foo foo=Mockito.mock(Foo.class)
TestSettings.Provider.get().setTestBeanProvider(Foo.class, foo);
Mockito.when(foo.functionInFoo()).thenReturn(XXX);
hitAUrl();
//do some testing here using xxx.

Test2
Foo foo=Mockito.mock(Foo.class)
TestSettings.Provider.get().setTestBeanProvider(Foo.class, foo);
Mockito.when(foo.functionInFoo()).thenReturn(YYY);
hitAUrl();
//do some testing here using YYY.

The variable foo is instantiated only once for the whole life time as it is part of the controller. So when I run my first test, the controller gets initialized when I hitAUrl() and it gets the mocked instance of Foo and returns XXX. But when I run the second test, it will still have the previous mock instance and return XXX again. I want it to return YYY. If I restart the server after Test1, it returns YYY. But this has to work without restarting. Please let me know how I can fix this. Any help is really appreciated.

user2116990
  • 51
  • 1
  • 6
  • This question is answered here (check the 2nd answer) http://stackoverflow.com/questions/4216569/how-to-tell-a-mockito-mock-object-to-return-something-different-the-next-time-it?rq=1 – Srikanta Jun 23 '15 at 13:38

2 Answers2

9

Mockito.when(foo.functionInFoo()).thenReturn(XXX, YYY);

This will return XXX when foo.functionUnFoo() is called for the first time and YYY every time after that.

Allan Pereira
  • 2,572
  • 4
  • 21
  • 28
Random
  • 909
  • 1
  • 9
  • 14
0

I am not sure that static factory methods can be mocked using Mockito. But I always use PowerMockito [ PowerMock + Mockito ] to mock static methods & private methods.

Foo foo = Mockito.mock(Foo.class);
PowerMockito.mockStatic(AFacftory.class);
PowerMockito.when(AFacftory.getFoo()).thenReturn(foo);
Stefan Birkner
  • 24,059
  • 12
  • 57
  • 72
kswaughs
  • 2,967
  • 1
  • 17
  • 21