英文:
how to skip fist when-then call in junit
问题
我想为类似于下面的Java代码编写一个Junit测试。在代码中,method()
被调用了2次。在我的Junit测试中,我有类似这样的代码 when(method()).thenThrow(exception);
但我想让这个 when-then 在第2次 method()
调用时触发,而不是在第1次 method()
调用时触发。那么,我该怎么做呢?
class Example {
public void example() {
OtherClass.method(); //第1次调用method()
/*
* 做一些其他操作
*/
OtherClass.method(); //第2次调用method()
}
}
英文:
I want to write a Junit test for a Java code similar to the code below. In the code, method()
is called 2 times. In my Junit test, I have something like this when(method()).thenThrow(exception);
but I want this when-then to be triggered on the 2nd method()
call, and not on the 1st method()
call. So, how can I do that?
class Example {
public void example() {
OtherClass.method(); //1st method call
/*
* doing something
*/
OtherClass.method(); //2nd method call
}
}
答案1
得分: 0
你可以使用 @Spy 来测试你的实例。
Spy 与模拟对象(mocks)类似,但你可以为同一类的某些方法设置存根(stub),用于测试。
编辑后,你可以简单地链接第二个存根。
when(method()).thenThrow(exception).thenThrow(exception);
英文:
You can use @Spy for your instance what are testing.
Spies are like mocks but you can stub some methods of the same class what you are testing
--well this answer was for your first question
After edit, you can just chain the second stub
when(method()).thenThrow(exception).thenThrow(exception);
答案2
得分: 0
你可以在模拟 void 方法时重复使用 Mockito 的 do...()
方法:
doNothing().doThrow(new RuntimeException("test")).when(mock).method();
如果对 method
进行多次调用,效果将按顺序发生。
英文:
You can repeat Mockito's do...()
methods when you mock a void method:
doNothing().doThrow(new RuntimeException("test")).when(mock).method();
The effects will happen in sequence if there are multiple calls to method
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论