我在我的服务中有这样的代码,我试图模拟execute(),context()和build():
Attributes attributes = targetClient.getAttributes(
TargetDeliveryRequest.builder()
.execute(new ExecuteRequest().mboxes(Collections.singletonList(mboxRequest)))
.context(new Context().channel(ChannelType.WEB)).build());
这个TargetDeliveryRequest第三方库,所以我不能在那里改变任何东西。
public class TargetDeliveryRequest {
....
public static TargetDeliveryRequestBuilder builder() {
return new TargetDeliveryRequestBuilder();
}
}
我试图模仿execute()、context()和build():
TargetDeliveryRequestBuilder targetDeliveryRequestBuilder = mock(TargetDeliveryRequestBuilder.class);
然而,这个TargetDeliveryRequestBuilder是一个final类,因此我在测试执行中得到了这个错误:
org.mockito.exceptions.base.MockitoException:无法模拟/监视类com.adobe.target.edge.client.model。TargetDeliveryRequestBuilder Mockito无法模拟/监视,因为:最后一堂课
public final class TargetDeliveryRequestBuilder {
...
TargetDeliveryRequestBuilder() {
}
...
public TargetDeliveryRequestBuilder context(Context context) {
this.request.context(context);
return this;
}
public TargetDeliveryRequestBuilder execute(ExecuteRequest execute) {
this.request.execute(execute);
return this;
}
...
public TargetDeliveryRequest build() {
this.setTargetValues();
this.setVisitorValues();
this.createVisitorId();
this.setExperienceCloudValues();
TargetDeliveryRequest targetDeliveryRequest = TargetDeliveryRequest.fromRequest(this.request);
targetDeliveryRequest.setLocationHint(this.locationHint);
targetDeliveryRequest.setSessionId(this.sessionId);
targetDeliveryRequest.setVisitor(this.visitor);
targetDeliveryRequest.setDecisioningMethod(this.decisioningMethod);
return targetDeliveryRequest;
}
...
}
我在Stackover上的其他问题中发现的唯一方法是添加mockito-inline('org.mockito:mockito-inline:3.12.4'),这使得我的测试工作得很好,然而,由于我的项目很旧,我添加mockito-inline的那一刻,它破坏了很多其他测试。换句话说,这对我来说不是一个选择。
类似问题:How to mock a final class with mockitoMockito cannot mock/spy because : - final class
有人知道如何模仿这段代码吗?谢谢
版本:Java:8个mockito核心:3.12.4 powermock-module-junit:2.0.9 powermock-api-mockito2:2.0.9
1条答案
按热度按时间f4t66c6m1#
我想出了如何使用PowerMockito解决这个问题,下面的代码: