简体   繁体   English

如何使用specs2模拟某些方法仅在第一次时抛出异常,然后什么也不做?

[英]How to mock some methods only throw exception for the first time and then do nothing, with specs2?

In specs2, we can mock a method and let it throw exception: 在specs2中,我们可以模拟方法并让其引发异常:

class Hello {
   def say():Unit = println("Hello, world")
}

val hello = mock[Hello]
hello.say() throws new RuntimeException("something wrong")

But how to make it just throw the first time, and then always do nothing? 但是,如何使其仅在第一次抛出后始终什么也不做呢?

This is actually a mockito question, not a specs2 one. 这实际上是一个模拟问题,而不是specs2问题。 From the mockito documentation: 从模拟文档:

when(mock.someMethod("some arg"))
   .thenThrow(new RuntimeException())
   .thenReturn("foo");

Alternative, shorter version of consecutive stubbing: 可选的,较短版本的连续存根:

 when(mock.someMethod("some arg"))
   .thenReturn("one", "two", "three");
doThrow(new RuntimeException("something wrong")).doNothing().when(hello).say()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM