我仅找到了三种方法来在Mockito(See documemantation)中启用STRICT_STUBS
MockitoJunitRunner
MockitoJUnit.rule().strictness(Strictness.STRICT_STUBS)
Mockito.mockitoSession()
.initMocks(this)
.strictness(Strictness.STRICT_STUBS)
.startMocking()
它们都需要通过注释(@Mock lateinit var api: MyApi
来声明存根。但是我正在使用mockito-kotlin并像这样声明存根:
val api: MyApi = mock()
或类似的话:
val api:MyApi = mock{
on { call("expected-param") } doReturn something
}
在引擎盖下,它使用Mockit.mock方法。
问题1 :使用Mockit.mock时如何启用STRICT_STUBS
?
问题2 :也许无论模拟如何定义,都可以对所有内容启用STRICT_STUBS
?
更新1 。测试示例
interface Foo {
fun doFoo(value: String): String
}
class Boo(private val foo: Foo) {
fun doBoo(value: String): String {
return foo.doFoo("$value with Boo")
}
}
class ExampleTest {
@get:Rule val rule = MockitoJUnit.rule().strictness(Strictness.STRICT_STUBS)
// doesn't work when replaced with var mockedFoo: Foo = Mockito.mock(Foo::class.java)
@Mock lateinit var mockedFoo: Foo
lateinit var booUnderTest: Boo
@Before fun setUp() {
booUnderTest = Boo(mockedFoo)
}
@Test fun withEmptyString() {
`when`(mockedFoo.doFoo(" with Boo")).thenReturn("empty boo")
// should fail, because this interaction is not used
`when`(mockedFoo.doFoo("Foo with Boo")).thenReturn("complete")
booUnderTest.doBoo("")
verifyNoMoreInteractions(mockedFoo)
}
@Test fun withRealString() {
`when`(mockedFoo.doFoo("Foo with Boo")).thenReturn("complete")
booUnderTest.doBoo("Foo")
// this test should pass because with STRICT stubbing no need to call verify
verifyNoMoreInteractions(mockedFoo)
}
}
当存根定义为@Mock lateinit var mockedFoo: Foo
时,严格存根有效。当我用var mockedFoo: Foo = Mockito.mock(Foo::class.java)
替换它时,严格的存根不再起作用。
更新2.答案。。 Mockito.mock
有效,如果在启用严格模式后调用。
class ExampleTest {
@get:Rule val rule = MockitoJUnit.rule().strictness(Strictness.STRICT_STUBS)
lateinit var mockedFoo: Foo
lateinit var booUnderTest: Boo
@Before fun setUp() {
mockedFoo = Mockito.mock(Foo::class.java)
booUnderTest = Boo(mockedFoo)
}
@Test fun withEmptyString() {
`when`(mockedFoo.doFoo(" with Boo")).thenReturn("empty boo")
// should fail, because this interaction is not used
`when`(mockedFoo.doFoo("Foo with Boo")).thenReturn("complete")
booUnderTest.doBoo("")
verifyNoMoreInteractions(mockedFoo)
}
@Test fun withRealString() {
`when`(mockedFoo.doFoo("Foo with Boo")).thenReturn("complete")
booUnderTest.doBoo("Foo")
// this test should pass because with STRICT stubbing no need to call verify
verifyNoMoreInteractions(mockedFoo)
}
}
答案 0 :(得分:0)
STRICT_STUBS需要额外的逻辑来验证在测试后已调用和未调用的内容,这就是为什么在整个测试级别上对其进行配置的原因。
话虽这么说,这三种方式中的任何一种都应该与普通的Mockito.mock
方法一起工作(并且在给定的示例中,它在后台使用了Mockito.mock
)。