我正在编写一个测试,以验证当从SOAP服务接收到不同响应时我的类的行为。我使用Jaxb,因此我的响应包含JaxbElements
,对于其中的许多元素,我需要编写模拟程序,如下所示:
JAXBElement<String> mock1 = mock(JAXBElement.class);
when(mock1.getValue()).thenReturn("a StringValue");
when(result.getSomeStringValue()).thenReturn(mock1);
JAXBElement<Integer> mock2 = mock(JAXBElement.class);
when(mock2.getValue()).thenReturn(new Integer(2));
when(result.getSomeIntValue()).thenReturn(mock2);
... <continue>
我想要做的是,重构这段代码的方式是:
when(result.getSomeStringValue())
.thenReturn(mockWithValue(JAXBElement.class, "a StringValue");
when(result.getSomeIntValue())
.thenReturn(mockWithValue(JAXBElement.class, 2));
并定义一个方法:
private <T> JAXBElement<T> mockWithValue(Class<JAXBElement> jaxbElementClass, T value) {
JAXBElement<T> mock = mock(jaxbElementClass);
when(mock.getValue()).thenReturn(value);
return mock;
}
在重构之前,执行代码时一切正常。但是,在重构之后执行代码时,我收到了以下错误:
org.mockito.exceptions.misusing.UnfinishedStubbingException:
Unfinished stubbing detected here:
-> at com.mypackage.ResultConverterTest.shouldConvertASuccessfulResponseWithAllTheElements(ResultConverterTest.java:126)
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
第126行是第一个调用mockWithValue
方法的地方。
所以问题是:有没有办法重复使用相同的代码来创建许多具有类似行为的模拟对象?