[英]Junit test for a method which calls another void method of another component
I have a method A (Check) on which it calls another void method B(wantToSkip). 我有一个方法A(检查),在它上面调用了另一个无效方法B(wantToSkip)。 A will throw one exception for which I am going to write junit test.
A将抛出一个异常,我将为此编写junit测试。 In this case want to avoid calling method B. How can I achieve that?
在这种情况下,要避免调用方法B。如何实现? Code is as below:
代码如下:
class A {
Class c = new Class();
Public void setC(C c) {
this.c = c;
}
String check(){
try{
//do something
} catch(Exception test) {
c.wantToSkip();
}
...
}
}
Here I just want to make sure exception test is thrown but want to skip calling method inside it. 在这里,我只想确保引发了异常测试,但想跳过其中的调用方法。 I tried following but did not work
我尝试关注但没有成功
@Test//(expected= Exception.class)
public void test(){
class c = Mockito.spy(new class());
Mockito.doNothing().when(c).wantToSkip();
check(some arguments);
}
If you provide a setter for Class c, you can use Mockito to achieve what you want to do. 如果提供了Class c的设置器,则可以使用Mockito实现您想要的操作。
Your unit test would look something like this: 您的单元测试将如下所示:
@Mock private Class mockC;
@Test
public void test(){
A a = new A();
a.setC(mockC);
a.check(some arguments);
}
Alternatively you could take your Class c
in the constructor, in which case your test could look like this. 或者,您可以将
Class c
放入构造函数中,在这种情况下,测试可能看起来像这样。
@Mock private Class mockC;
@Test
public void test(){
A a = new A(mockC);
a.check(some arguments);
}
The mockC has no behaviour specified for when c.wantToSkip()
is called, so it won't do anything. 当
c.wantToSkip()
时, c.wantToSkip()
没有指定行为,因此它不会做任何事情。
The latest non-beta version for mockito is here: http://mvnrepository.com/artifact/org.mockito/mockito-all/1.10.19 Mockito的最新非Beta版本在这里: http : //mvnrepository.com/artifact/org.mockito/mockito-all/1.10.19
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.