如何在JUnit中跳过第一个 when-then 调用

huangapple go评论75阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年7月7日 07:12:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/76633034.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定