gpt4 book ai didi

java - Mockito - 如何监视 doAnswer 中的调用参数

转载 作者:行者123 更新时间:2023-11-30 08:13:08 26 4
gpt4 key购买 nike

这是我第一天使用 Mockito 编写单元测试,我可能从一个复杂的练习开始。

下面是我的类结构,我正在为 Class2.targetMethod() 编写测试。 Class1 静态方法修改传入的对象而不是返回任何结果。

class Class1 {
static void dbquery(OutParam out) {
// Complex code to fill in db results in OutParam object
}
}

class Class2 {
void targetMethod() {
OutParam p1 = new OutParam1();
Class1.dbquery(p1);
ResultSet rs = p1.getCursor();
...
}
}

下面是我的测试设置:

@RunWith(PowerMockRunner.class)
@PrepareForTest({Class1.class, Class2.class})
public class Class2Test {
@Before
public void setUp() throws Exception {

PowerMockito.mockStatic(Class1.class);

doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Exception {
OutParam result = (OutParam)invocation.getArguments()[1];
OutParam spy = spy(result);
ResultSet mockResult = mock(ResultSet.class);
doReturn(mockResult).when(spy.getCursor());
when(mockResult.getString("some_id")).thenReturn("first_id","second_id");
when(mockResult.getString("name")).thenReturn("name1","name2");

return null;
}
}).when(Class1.class, "dbquery", any());
}
}

但是测试失败并出现以下异常 - 主要是由于“doReturn”行。

关于这个问题的任何建议或者我的方法是否完全错误。

org.mockito.exceptions.misusing.UnfinishedStubbingException: 
Unfinished stubbing detected here:

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!
3: you are stubbing the behaviour of another mock inside before 'thenReturn' instruction if completed

最佳答案

语法:

doReturn(mockResult).when(spy.getCursor());

应该是:

doReturn(mockResult).when(spy).getCursor();

通过仅使用 spy 而不是 spy.getCursor() 调用 when,您可以让 Mockito 有机会暂时停用 getCursor 这样您就可以在不调用真实对象的情况下 stub 它。尽管这在这里似乎并不重要,但 Mockito 坚持要在 doAnswer(等)之后对 when 的调用保持这种模式。

关于java - Mockito - 如何监视 doAnswer 中的调用参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30116783/

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