考虑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没有被传递给所需类型的对象。
答案 0 :(得分:1)
似乎混淆了类型推断。
使用thenAnswer
(或缩短then
)。
when(mockCnpOnlineResponse.getTransactionResponse()).then(i -> authorization);
i -> authorization
是一个lambda表达式,用Answer<? extends TransactionTypeWithReportGroup>
评估一个能够匹配的捕获。