在运行测试时,我得到了以下异常。我正在使用Mockito进行模仿。Mockito库提到的提示无济于事。
org.mockito.exceptions.misusing.UnfinishedStubbingException:
Unfinished stubbing detected here:
-> at com.a.b.DomainTestFactory.myTest(DomainTestFactory.java:355)
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, you naughty developer!
at a.b.DomainTestFactory.myTest(DomainTestFactory.java:276)
..........
来自DomainTestFactory
的测试代码。当我运行下面的测试时,我看到了异常。
@Test
public myTest(){
MyMainModel mainModel = Mockito.mock(MyMainModel.class);
Mockito.when(mainModel.getList()).thenReturn(getSomeList()); // Line 355
}
private List<SomeModel> getSomeList() {
SomeModel model = Mockito.mock(SomeModel.class);
Mockito.when(model.getName()).thenReturn("SomeName"); // Line 276
Mockito.when(model.getAddress()).thenReturn("Address");
return Arrays.asList(model);
}
public class SomeModel extends SomeInputModel{
protected String address;
protected List<SomeClass> properties;
public SomeModel() {
this.Properties = new java.util.ArrayList<SomeClass>();
}
public String getAddress() {
return this.address;
}
}
public class SomeInputModel{
public NetworkInputModel() {
this.Properties = new java.util.ArrayList<SomeClass>();
}
protected String Name;
protected List<SomeClass> properties;
public String getName() {
return this.Name;
}
public void setName(String value) {
this.Name = value;
}
}
发布于 2021-02-05 01:38:32
对于那些使用com.nhaarman.mockitokotlin2.mock {}
的用户
解决方法%1
例如,当我们在另一个mock中创建一个mock时,就会发生此错误
mock {
on { x() } doReturn mock {
on { y() } doReturn z()
}
}
解决方案是在一个变量中创建子mock,并在父mock的作用域中使用该变量,以防止mock创建被显式嵌套。
val liveDataMock = mock {
on { y() } doReturn z()
}
mock {
on { x() } doReturn liveDataMock
}
解决方法2
确保所有应该有thenReturn
的mock都有一个thenReturn
。
总帐
发布于 2019-10-10 20:13:40
org.mockito.exceptions.misusing.UnfinishedStubbingException:
Unfinished stubbing detected here:
E.g. thenReturn() may be missing.
要模拟void方法,请尝试下面的方法:
//Kotlin Syntax
Mockito.`when`(voidMethodCall())
.then {
Unit //Do Nothing
}
发布于 2021-08-17 05:47:01
请阅读这篇article,它有特殊的解释和工作方法。此外,该问题的另一个可能原因和修复它的解决方案是将实际的模拟转移到测试的早期阶段。
https://stackoverflow.com/questions/26318569
复制相似问题