如何告诉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.
推荐答案
首先不要制作模拟静态。使它成为一个私人领域。只需将您的setUp类放入 @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屋!