![](/img/trans.png)
[英]How to test with PowerMock a method which calls another private void method from the same class?
[英]Junit test for a method which calls another void method of another component
我有一個方法A(檢查),在它上面調用了另一個無效方法B(wantToSkip)。 A將拋出一個異常,我將為此編寫junit測試。 在這種情況下,要避免調用方法B。如何實現? 代碼如下:
class A {
Class c = new Class();
Public void setC(C c) {
this.c = c;
}
String check(){
try{
//do something
} catch(Exception test) {
c.wantToSkip();
}
...
}
}
在這里,我只想確保引發了異常測試,但想跳過其中的調用方法。 我嘗試關注但沒有成功
@Test//(expected= Exception.class)
public void test(){
class c = Mockito.spy(new class());
Mockito.doNothing().when(c).wantToSkip();
check(some arguments);
}
如果提供了Class c的設置器,則可以使用Mockito實現您想要的操作。
您的單元測試將如下所示:
@Mock private Class mockC;
@Test
public void test(){
A a = new A();
a.setC(mockC);
a.check(some arguments);
}
或者,您可以將Class c
放入構造函數中,在這種情況下,測試可能看起來像這樣。
@Mock private Class mockC;
@Test
public void test(){
A a = new A(mockC);
a.check(some arguments);
}
當c.wantToSkip()
時, c.wantToSkip()
沒有指定行為,因此它不會做任何事情。
Mockito的最新非Beta版本在這里: http : //mvnrepository.com/artifact/org.mockito/mockito-all/1.10.19
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.