【发布时间】:2015-06-23 07:33:32
【问题描述】:
我想使用 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.
变量 foo 在整个生命周期内只实例化一次,因为它是控制器的一部分。 所以当我运行我的第一个测试时,控制器在我 hitAUrl() 时被初始化,它获取 Foo 的模拟实例并返回 XXX。但是当我运行第二个测试时,它仍然会有之前的模拟实例并再次返回 XXX。我希望它返回 YYY。如果我在 Test1 之后重新启动服务器,它会返回 YYY。但这必须在不重新启动的情况下工作。请让我知道如何解决此问题。非常感谢任何帮助。
【问题讨论】:
-
这里回答了这个问题(查看第二个答案)stackoverflow.com/questions/4216569/…
标签: unit-testing testing junit mocking mockito