gpt4 book ai didi

android - Mockito Stubbed Spy 有时会调用有时不会调用被侦测对象的方法

转载 作者:行者123 更新时间:2023-11-29 02:32:24 29 4
gpt4 key购买 nike

问题

@Test中,我怎样才能同时实现这两者;

  1. 从被测 Kotlin 类中调用真正的方法
  2. 将它对此类被测类中的其他方法所做的内部调用 stub 。

情景

我正在使用以下库;

testCompile "com.nhaarman:mockito-kotlin:1.5.0"
testCompile "org.mockito:mockito-inline:2.12.0"

我还有一个简单的 kotlin 类,形式为

class MyClass() {

fun parentFunc() {
funA()
}

fun funA() {
//DOES SOMETHING WHICH I ASSUME IS IRRELEVANT FOR ANSWERING THE QUESTION
}
}

使用 spy 进行测试

@Test
fun myTest() {
val myClassSpy = spy(MyClass())
Mockito.doNothing().`when`(myClassSpy.funA())
//Mockito.doNothing().whenever(myClassSpy.funA()) also throws the same error

myClassSpy.parentFunc()

verify(myClassSpy, times(1)).funA()
}

抛出错误,

org.mockito.exceptions.misusing.UnfinishedStubbingException: 
Unfinished stubbing detected here:
-> at com.nhaarman.mockito_kotlin.MockitoKt.doNothing(Mockito.kt:108)

E.g. thenReturn() may be missing.
Examples of correct stubbing:
when(mock.isOk()).thenReturn(true);
when(mock.isOk()).thenThrow(exception);
doThrow(exception).when(mock).someVoidMethod();
Hints:
1. missing thenReturn()
2. you are trying to stub a final method, which is not supported
3: you are stubbing the behaviour of another mock inside before 'thenReturn' instruction if completed

另一个测试用例;

@Test
fun myTest() {
val myClassSpy = Mockito.spy(MyClass())

myClassSpy.parentFunc()

verify(myClassSpy, times(1)).funA()
}

出现以下错误:

Wanted but not invoked:
myClass.funA();

However, there was exactly 1 interaction with this mock:
myClass.parentFunc();

此外,每当我尝试使用调试器调用 myClassSpy 方法或与之相关的东西时,它都会抛出以下错误:

com.sun.jdi.InternalException : Unexpected JDWP Error: 41

enter image description here

我尝试过使用

Mockito.`when`(myClassSpy.funA()).then { }
Mockito.`when`(myClassSpy.funA()).thenAnswer { }
Mockito.`when`(myClassSpy.funA()).thenReturn(Unit)

用模拟测试

模拟整个类在这种情况下不起作用,因为它是一个模拟并且不会调用被测的真实方法:

@Test
fun myTest() {
val myMock: MyClass = mock()

myMock.parentFunc()

verify(myMock, times(1)).funA()
}

同样的错误:

Wanted but not invoked:
myClass.funA();

However, there was exactly 1 interaction with this mock:
myClass.parentFunc();

如果我进一步调用真正的方法,它也会显示相同的 想要但未调用 myClass.funA(); 错误:

@Test
fun myTest() {
val myMock: MyClass = mock()

Mockito.`when`(myMock.parentFunc()).thenCallRealMethod()

myMock.parentFunc()

verify(myMock, times(1)).funA()
}

我也尝试打开 MyClass 但抛出了同样的错误。

因此,我如何 stub 来自 spy 的方法,以便当我测试来自此类 spy 对象的方法时,它不会将调用传播到我不想进一步模拟的其他方法。

非常感谢任何帮助、建议、想法...以测试这些类型的方法。

最佳答案

对我来说,用 mockito 模拟 kotlin 类有时有效,有时无效,所以我通常做的是为该类提取一个,这总是有效的。

模拟也用于测试交互,所以你不应该在你正在测试的同一个类上模拟一个方法,而是在你传递给构造函数的不同类上模拟一个方法(依赖注入(inject))然后你可以在测试时注入(inject)一个模拟和正确的生产时的依赖。

class MyTestedClass(val funManager:MyUsedClass) {    
fun parentFunc() {
funManager.funA()
}
}

关于android - Mockito Stubbed Spy 有时会调用有时不会调用被侦测对象的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48839202/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com