gpt4 book ai didi

java - 如何为 Resttemplate postForObject 方法编写 mockito junit

转载 作者:行者123 更新时间:2023-11-30 07:50:57 25 4
gpt4 key购买 nike

我正在尝试将消息列表发布到其余 api。如何为下面的 postJSONData 方法编写 mockito junit:

public class PostDataService{

@Autowired
RestTemplate restTemplate;

@Autowired
private Environment env;

private HttpEntity<String> httpEntity;

private HttpHeaders httpHeaders;

private String resourceURL = null;

public PostDataService(){
httpHeaders = new HttpHeaders();
httpHeaders.set("Content-Type", "application/json");
}

public void postJSONData(List<String> data){
try
{
resourceURL = env.getProperty("baseURL") + env.getProperty("resourcePath");
httpEntity = new HttpEntity<String>(data.toString(), httpHeaders);
String response = restTemplate.postForObject(resourceURL, httpEntity, String.class);
}
catch (RestClientException e) {
LOGGER.info("ErrorMessage::" + e.getMessage());
LOGGER.info("ErrorCause::" + e.getCause());
}
}


}

请教我怎么写。

最佳答案

您可以使用 Mockito 来:

  • 使用模拟的 RestTemplateEnvironment 创建 postData 的实例
  • 对这些设置期望以允许 ``postJSONData` 调用完成
  • 验证模拟的 RestTemplate 是否被正确调用

postJSONData 方法不使用 restTemplate.postForObject() 响应,因此就测试此方法而言,您可以做的最好的事情是验证 restTemplate .postForObject() 使用正确的参数调用。

这是一个例子:

@RunWith(MockitoJUnitRunner.class)
public class PostDataTest {

@Mock
private RestTemplate restTemplate;
@Mock
private Environment env;

@InjectMocks
private PostData postData;

@Test
public void test_postJSONData() {
String baseUrl = "theBaseUrl";
String resourcePath = "aResourcePath";

Mockito.when(env.getProperty("baseURL")).thenReturn(baseUrl);
Mockito.when(env.getProperty("resourcePath")).thenReturn(resourcePath);

List<String> payload = new ArrayList<>();

postData.postJSONData(payload);

// it's unclear from your posted code what goes into the HttpEntity so
// this approach is lenient about its expectation
Mockito.verify(restTemplate).postForObject(
Mockito.eq(baseUrl + resourcePath),
Mockito.any(HttpEntity.class),
Mockito.eq(String.class)
);

// assuming that the HttpEntity is constructed from the payload passed
// into postJSONData then this approach is more specific
HttpHeaders headers = new HttpHeaders();
headers.set("Content-Type", "application/json");
Mockito.verify(restTemplate).postForObject(
Mockito.eq(baseUrl + resourcePath),
Mockito.eq(new HttpEntity<>(payload.toString(), headers)),
Mockito.eq(String.class)
);
}
}

旁注; postData 是类的不寻常名称,您的 OP 中提供的 postJSONData 方法无法编译;它引用 meterReadings 而不是 data

关于java - 如何为 Resttemplate postForObject 方法编写 mockito junit,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47591224/

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