問題描述
我有一個(gè)類似下面的代碼:
I have a code somewhat like this below:
Class A {
public boolean myMethod(someargs) {
MyQueryClass query = new MyQueryClass();
Long id = query.getNextId();
// some more code
}
}
Class MyQueryClass {
....
public Long getNextId() {
//lot of DB code, execute some DB query
return id;
}
}
現(xiàn)在我正在為 A.myMethod(someargs)
編寫測(cè)試.我想跳過真正的方法 query.getNextId()
而是返回一個(gè)存根值.基本上,我想模擬 MyQueryClass
.
Now I'am writing a test for A.myMethod(someargs)
. I want to skip the real method query.getNextId()
and instead return a stub value. Basically, I want to mock MyQueryClass
.
所以在我的測(cè)試用例中,我使用了:
So in my test case, I have used:
MyQueryClass query = PowerMockito.mock(MyQueryClass.class);
PowerMockito.whenNew(MyQueryClass.class).withNoArguments().thenReturn(query);
when(query.getNextId()).thenReturn(1000000L);
boolean b = A.getInstance().myMethod(args);
//asserts
我在測(cè)試類的開頭使用了 @RunWith(PowerMockRunner.class)
和 @PrepareForTest({MyQueryClass.class})
.
I used @RunWith(PowerMockRunner.class)
and @PrepareForTest({MyQueryClass.class})
in the beginning of my test class.
但是我調(diào)試測(cè)試的時(shí)候,還是調(diào)用了MyQueryClass
類的真實(shí)方法getNextId()
.
But when I debug the test, it is still calling the real method getNextId()
of the MyQueryClass
class.
我在這里缺少什么?任何人都可以提供幫助,因?yàn)槲沂?Mockito 和 PowerMockito 的新手.
What am I missing here? Can anyone help as I am new to Mockito and PowerMockito.
推薦答案
需要將調(diào)用構(gòu)造函數(shù)的類放到@PrepareForTest
注解中,而不是正在構(gòu)造的類 - 請(qǐng)參閱 模擬新對(duì)象的構(gòu)造.
You need to put the class where the constructor is called into the @PrepareForTest
annotation instead of the class which is being constructed - see Mock construction of new objects.
在你的情況下:
? @PrepareForTest(MyQueryClass.class)
? @PrepareForTest(A.class)
更籠統(tǒng)的:
? @PrepareForTest(NewInstanceClass.class)
? @PrepareForTest(ClassThatCreatesTheNewInstance.class)
這篇關(guān)于使用 PowerMockito.whenNew() 不會(huì)被嘲笑,而是調(diào)用原始方法的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!