添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
相关文章推荐
叛逆的太阳  ·  ​HUAWEI VR Glass ...·  9 月前    · 
腼腆的伏特加  ·  古火山_百度百科·  1 年前    · 
绅士的长颈鹿  ·  苏州网红“日本街”·  2 年前    · 

我怎样才能跳过用MockK或Mockito运行一个方法呢?

0 人关注

当我只想测试一个方法在其他方法中被调用时,我怎样才能做到这一点?我不希望该方法在被调用后运行。

fun aMethod(){
   bMethod()
fun bMethod(){
   // complex 

I tried this. but didn't work.

@Test
fun test(){
    coEvery{ mClass.bMethod() } just runs
    mClass.aMethod()
    verify { mClass.bMethod() wasNot Called }
@Test
fun test(){
    coEvery{ mClass.bMethod() } returns Unit
    mClass.aMethod()
    verify { mClass.bMethod() wasNot Called }
@Test
fun test(){
    coEvery{ mClass.bMethod() } answers { Unit }
    mClass.aMethod()
    verify { mClass.bMethod() wasNot Called }

我还尝试用called代替Called(小写和大写C)。

他们都没有工作。我怎样才能解决这个问题呢?

2 个评论
c-an
@Demigod 我可以嘲讽。你是什么意思?我只想知道怎样才能一无所获。
c-an
@Demigod 我不明白,mClass已经是模拟类了。你能给出更详细的答案吗?当返回值不是空的时候,它是有效的。我不明白你的意思。
android
kotlin
junit
mockito
mockk
c-an
c-an
发布于 2022-08-02
2 个回答
Nilzor
Nilzor
发布于 2022-08-11
0 人赞同

Solution with Mockito using mockito-kotlin 其中两个方法都是同一个类的一部分。

class ExampleUnitTest {
    @Test
    fun mockOneMethod() {
        val mock = mock<TheClass>()
        whenever(mock.aMethod()).thenCallRealMethod()
        mock.aMethod()
        verify(mock, times(1)).bMethod()
open class TheClass {
    open fun aMethod(){
        System.out.println("a called")
        bMethod()
    open fun bMethod() {
        throw NotImplementedError()

请注意,被测试的方法必须是open,以便mockito能够改变它们。

比 "thenCallRealMethod "更好的选择可能是重构这个类,使aMethodbMethod在两个不同的类中。然后你将模拟包含bMethod的类的全部内容。

Karsten Gabriel
Karsten Gabriel
发布于 2022-08-11
0 人赞同

在你的问题中,有一堆问题或事情是不清楚的。

  • You do not need to use coEvery to stub bMethod , because it is not a suspend function. You can see that by the fact that there is no suspend keyword at the start of the declaration of bMethod . You can and should use the regular every instead.
  • verify { xy wasNot Called } is used to verify that none of the functions of a mock xy are called. If you want to verify that your single function bMethod was not called, you should instead check that it was called zero times:
  • verify(exactly = 0) { mClass.bMethod() }