gpt4 book ai didi

java - 如何模拟 ResponseEntity

转载 作者:行者123 更新时间:2023-12-01 21:29:46 25 4
gpt4 key购买 nike

请找到下面提到的代码:我需要帮助为 ResponseEntity 编写 Mockito 条件:

if(isObjectPresent(ePartnerRestRequestDTO)) 
{

ePartnerRestRequestDTO.setLoggerId(loggerId);
String url = new StringBuilder(EPARTNER_MICRO_SERVICE_URL).append(service).toString();
RequestEntity<String> requestEntity = new RequestEntity<String>(prePreocess(ePartnerRestRequestDTO), HttpMethod.POST, new URI(url));

Instant before = Instant.now();
ResponseEntity<String> response = new RestTemplate().exchange(requestEntity, String.class);
logger.info("ePartner service " + url + " - duration (milliseconds) :: " + Duration.between(before, Instant.now()).toMillis());

if(isObjectPresent(response) && isObjectPresent(response.getStatusCode()) && HttpStatus.OK == response.getStatusCode()) {
ePartnerRestResponseDTO = postProcess(JWSResponseUtil.verifyJWSSignatureAndExtractPayload(response.getBody()));

if(isObjectPresent(ePartnerRestResponseDTO) && isValuePresent(ePartnerRestResponseDTO.getResponseCode())) {

if(SUCCESS_CODE.equals(ePartnerRestResponseDTO.getResponseCode())) {
status = true;
}
}
}
}

最佳答案

您无法使用普通 Mockito 模拟 NEW 对象的创建。

1) 我建议将对象的创建转移到包级别方法:

RequestEntity<String> getRequestEntity(/* params */){
return new RequestEntity<String>(prePreocess(ePartnerRestRequestDTO),
HttpMethod.POST, new URI(url))
}

2) 然后监视被测试的类

@Spy
private ClassUnderTest classUnderTestSpy;

@Before
public void init(){
MockitoAnnotations.initMocks(this);

doReturn(myPreparedRequestEntity).when(classUnderTestSpy).getRequestEntity(/* params*/);
}

关于java - 如何模拟 ResponseEntity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58817110/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com