問題描述
所以,我在類級別創建一個模擬對象作為靜態變量,就像這樣......在一個測試中,我希望 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.
推薦答案
首先不要讓 mock 靜態化.將其設為私有字段.只需將您的設置類放在 @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 模擬對象在下次調用時返回不同的東西?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!