如何告诉 Mockito 模拟对象在下次调用时返回不同的内容? [英] How to tell a Mockito mock object to return something different the next time it is called?
问题描述
所以,我像这样在类级别上创建一个模拟对象作为静态变量......在一个测试中,我希望 Foo.someMethod()
返回某个值,而在另一个测试中,我希望它返回不同的值.我遇到的问题是,似乎我需要重建模拟才能使其正常工作.我想避免重建模拟,而只是在每个测试中使用相同的对象.
So, I'm creating a mock object as a static variable on the class level like so... In one test, I want Foo.someMethod()
to return a certain value, while in another test, I want it to return a different value. The problem I'm having is that it seems I need to rebuild the mocks to get this to work correctly. I'd like to avoid rebuilding the mocks, and just use the same objects in each test.
class TestClass {
private static Foo mockFoo;
@BeforeClass
public static void setUp() {
mockFoo = mock(Foo.class);
}
@Test
public void test1() {
when(mockFoo.someMethod()).thenReturn(0);
TestObject testObj = new TestObject(mockFoo);
testObj.bar(); // calls mockFoo.someMethod(), receiving 0 as the value
}
@Test
public void test2() {
when(mockFoo.someMethod()).thenReturn(1);
TestObject testObj = new TestObject(mockFoo);
testObj.bar(); // calls mockFoo.someMethod(), STILL receiving 0 as the value, instead of expected 1.
}
}
在第二个测试中,当 testObj.bar() 被调用时,我仍然收到 0 作为值......解决这个问题的最佳方法是什么?请注意,我知道我可以在每个测试中使用不同的 Foo
模拟,但是,我必须从 mockFoo
链接多个请求,这意味着我必须执行在每个测试中链接.
In the second test, I'm still receiving 0 as the value when testObj.bar() is called... What is the best way to resolve this? Note that I know I could use a different mock of Foo
in each test, however, I have to chain multiple requests off of mockFoo
, meaning I'd have to do the chaining in each test.
推荐答案
首先不要使模拟静态化.使其成为私人领域.只需将您的设置类放在 @Before
中,而不是 @BeforeClass
.它可能会运行一堆,但它很便宜.
First of all don't make the mock static. Make it a private field. Just put your setUp class in the @Before
not @BeforeClass
. It might be run a bunch, but it's cheap.
其次,您现在拥有的方式是让模拟根据测试返回不同内容的正确方法.
Secondly, the way you have it right now is the correct way to get a mock to return something different depending on the test.
这篇关于如何告诉 Mockito 模拟对象在下次调用时返回不同的内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!