Using Mockito for multiple calls to the same method and different outputs

advertisements

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.


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.