[英]Having Issues Mocking “marshalSendandReceive” method call in Mockito
我试图在Mockito中创建一些单元测试,并模拟返回JAXBElement的WebServiceTemplate调用。 我不断遇到NullPointerException以及内部Mockito错误。 如何成功模拟Mockito中的方法调用?
我研究了StackOverflow中的其他一些问题,尽管其中一些问题相似,但没有一个提供成功的模拟和测试。 我的测试仍然失败。
这是我的实际代码中SearchInvoker.class中的方法调用。
JAXBElement<SearchResponse> response = null;
JAXBElement<SearchRequest> req = soapClient.genConn(searchReq);
try {
response = (JAXBElement<SearchResponse>) getWebServiceTemplate().marshalSendAndReceive(req, new SoapActionCallback("search"));
} catch (RuntimeException e) {
throw new Exception(e);
}
这是我尝试模拟通话的方式。
public class SearchInvokerTest extends PackageTest{
@InjectMocks private SearchInvoker invoker;
@Mock private SearchSoapClient soapClient;
@Mock private WebServiceOperations template;
@Test
public void searchInvokerTest() throws Exception {
ObjectFactory factory = new ObjectFactory();
doReturn(factory.createSearchResponse(generateAwsSearchRsp())).when(template.marshalSendAndReceive(any(JAXBElement.class), any(WebServiceMessageCallback.class)));
SearchResponse rsp = invoker.doSearch(new SearchRequestDVO());
assertNotNull(rsp);
assertEquals("123", rsp.getTraceID());
}
}
我有“ when”和“ doReturn”语句的地方,我有一个NullPointer以及Mockito的内部错误。 我希望能够返回模拟的类。
这是我运行mvn test时错误的堆栈跟踪:
[ERROR] Tests run: 2, Failures: 0, Errors: 2, Skipped: 0, Time elapsed: 0.018 s <<< FAILURE! - in SearchInvokerTest
[ERROR] searchInvokerTest(SearchInvokerTest) Time elapsed: 0.002 s <<< ERROR!
java.lang.NullPointerException
at SearchInvokerTest.searchInvokerTest(SearchInvokerTest.java:33)
[ERROR] searchInvokerTest(SearchInvokerTest) Time elapsed: 0.017 s <<< ERROR!
org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Misplaced or misused argument matcher detected here:
-> at SearchInvokerTest.searchInvokerTest(SymcorSearchInvokerTest.java:33)
-> at SearchInvokerTest.searchInvokerTest(SymcorSearchInvokerTest.java:33)
You cannot use argument matchers outside of verification or stubbing.
Examples of correct usage of argument matchers:
when(mock.get(anyInt())).thenReturn(null);
doThrow(new RuntimeException()).when(mock).someVoidMethod(anyObject());
verify(mock).someMethod(contains("foo"))
This message may appear after an NullPointerException if the last matcher is returning an object
like any() but the stubbed method signature expect a primitive argument, in this case,
use primitive alternatives.
when(mock.get(any())); // bad use, will raise NPE
when(mock.get(anyInt())); // correct usage use
Also, this error might show up because you use argument matchers with methods that cannot be mocked.
Following methods *cannot* be stubbed/verified: final/private/equals()/hashCode().
Mocking methods declared on non-public parent classes is not supported.
该错误信息表明您的模拟尚未初始化。
您必须告诉JUnit与Mockito运行程序一起运行:
[...]
@RunWith(MockitoJRunner.class)
public class SearchInvokerTest extends PackageTest {
[...]
}
除其他外,这将初始化您的模拟。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.