[英]How to JSON-marshal JAXBElement-wrapped responses without the JAXBElement wrapper?
[英]How to mock an object wrapped in a JAXBElement
考虑一下JAXB生成的以下代码:
public class CnpOnlineResponse {
protected JAXBElement<? extends TransactionTypeWithReportGroup> transactionResponse;
public JAXBElement<? extends TransactionTypeWithReportGroup> getTransactionResponse() {
return transactionResponse;
}
public void setTransactionResponse(JAXBElement<? extends TransactionTypeWithReportGroup> value) {
this.transactionResponse = value;
}
}
public class AuthorizationResponse extends TransactionTypeWithReportGroup {
}
public class ObjectFactory {
public JAXBElement<AuthorizationResponse> createAuthorizationResponse(AuthorizationResponse value) {
return new JAXBElement<AuthorizationResponse>(_AuthorizationResponse_QNAME, AuthorizationResponse.class, null, value);
}
}
我正在编写一个测试,其中我同时模拟了CnpOnlineResponse和AuthorizationResponse:
@Mock private CnpOnlineResponse mockCnpOnlineResponse;
@Mock private AuthorizationResponse mockAuthorizationResponse;
final JAXBElement<AuthorizationResponse> authorization = CnpContext.getObjectFactory().createAuthorizationResponse(mockAuthorizationResponse);
when(mockCnpOnlineResponse.getTransactionResponse()).thenReturn(authorization); // <= ERROR here
但是我收到以下编译错误:
The method thenReturn(JAXBElement<capture#1-of ? extends TransactionTypeWithReportGroup>) in the type OngoingStubbing<JAXBElement<capture#1-of ? extends TransactionTypeWithReportGroup>> is not applicable for the arguments (JAXBElement<AuthorizationResponse>)
任何帮助表示赞赏,我不明白为什么它认为没有将thenReturn传递给所需类型的对象。
似乎混淆了类型推断。
使用thenAnswer
(或短then
)。
when(mockCnpOnlineResponse.getTransactionResponse()).then(i -> authorization);
i -> authorization
是评估为Answer<? extends TransactionTypeWithReportGroup>
的lambda表达式Answer<? extends TransactionTypeWithReportGroup>
Answer<? extends TransactionTypeWithReportGroup>
使其能够匹配的捕获。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.