問(wèn)題描述
我正在嘗試使用 Mockito/JUnit 為這樣的函數(shù)編寫(xiě)單元測(cè)試:
I'm trying to write unit tests with Mockito / JUnit for a function like this:
class1 {
method {
object1 = class2.method // method that I want to fake the return value
// some code that I still want to run
}
}
在 Mockito 中有什么方法可以存根 class2.method 的結(jié)果嗎?我正在嘗試提高 class1 的代碼覆蓋率,因此我需要調(diào)用它的實(shí)際生產(chǎn)方法.
Is there any way in Mockito to stub the result of class2.method? I'm trying to improve code coverage for class1 so I need to call its real production methods.
我查看了 Mockito API 的 spy 方法,但這會(huì)覆蓋整個(gè)方法,而不是我想要的部分.
I looked into the Mockito API at its spy method but that would overwrite the whole method and not the part that I want.
推薦答案
我想我理解你的問(wèn)題.讓我重新表述一下,您有一個(gè)正在嘗試測(cè)試的函數(shù),并且想要模擬在該函數(shù)中調(diào)用的函數(shù)的結(jié)果,但在不同的類(lèi)中.我已經(jīng)通過(guò)以下方式處理了.
I think I am understanding your question. Let me re-phrase, you have a function that you are trying to test and want to mock the results of a function called within that function, but in a different class. I have handled that in the following way.
public MyUnitTest {
private static final MyClass2 class2 = mock(MyClass2.class);
@Begin
public void setupTests() {
when(class2.get(1000)).thenReturn(new User(1000, "John"));
when(class2.validateObject(anyObj()).thenReturn(true);
}
@Test
public void testFunctionCall() {
String out = myClass.functionCall();
assertThat(out).isEqualTo("Output");
}
}
這樣做是在使用 @Before 注釋包裝的函數(shù)中,我正在設(shè)置我希望 class2 中的函數(shù)如何響應(yīng)給定的特定輸入.然后,在實(shí)際測(cè)試中,我只是在我想要測(cè)試的類(lèi)中調(diào)用我試圖測(cè)試的函數(shù).在這種情況下,myClass.functionCall() 正常運(yùn)行,您不會(huì)覆蓋它的任何方法,而只是模擬它從 MyClass2 中的方法(或方法)獲得的輸出.
What this is doing is that within the function wrapped with the @Before annotation, I am setting up how I want the functions in class2 to respond given specific inputs. Then, from within the actual test, I am just calling the function that I am trying to test in the class I want to test. In this case, the myClass.functionCall() is running through as normal and you are not overwriting any of its methods, but you are just mocking the outputs that it gets from the methods (or method) within MyClass2.
這篇關(guān)于使用 Mockito 在另一個(gè)類(lèi)中模擬一個(gè)類(lèi)方法的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!