小编use*_*990的帖子

使用Mockito对同一方法和不同输出进行多次调用

我想使用mockito和stub方法.我希望方法基于存根返回不同的值.但它总是返回第一个输出.以下是我的设置

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.
Run Code Online (Sandbox Code Playgroud)

变量foo在整个生命周期中仅实例化一次,因为它是控制器的一部分.因此,当我运行我的第一个测试时,控制器在我hitUrl()时被初始化,并且它获得了Foo的模拟实例并返回XXX.但是当我运行第二个测试时,它仍然会有前一个模拟实例并再次返回XXX.我想让它回归YYY.如果我在Test1之后重新启动服务器,它将返回YYY.但这必须在不重新启动的情况下工作.请让我知道如何解决这个问题.任何帮助都非常感谢.

testing junit unit-testing mocking mockito

2
推荐指数
1
解决办法
1749
查看次数

标签 统计

junit ×1

mocking ×1

mockito ×1

testing ×1

unit-testing ×1