【发布时间】:2020-01-26 18:07:18
【问题描述】:
我正在使用 RestTemplate exchange HttpMethod.POST 方法 POST 到端点。在我的测试文件中,我正在测试 POST 方法的 success。然而,在我目前的测试中,当发出 POST 请求时,我得到了401 Unauthorized error。在测试文件中发出 POST 请求时,我需要帮助来模拟 API
这是我的主要文件
@Component
public class DataTestRepo {
private final RestTemplate restTemplate;
private final String url;
private final AllBuilder headersBuilder;
public DataTestRepo(
@Qualifier(Oauth.BEAN_NAME) AllBuilder headersBuilder,
RestTemplate restTemplate, String url) {
this.headersBuilder = headersBuilder;
this.restTemplate = restTemplate;
this.url = url;
}
public ResponseEntity<String> postJson(Set<String> results) {
ResponseEntity<String> result = null;
try {
JSONObject jsonObject = new JSONObject(body);
HttpEntity<String> request = new HttpEntity<String>(jsonObject.toString(), null);
restTemplate.getMessageConverters().add(stringConvertor);
result = restTemplate.exchange(url, HttpMethod.POST,
new HttpEntity<>(request, getHttpHeaders()), String.class);
}
return result;
}
}
这是我的测试文件
@RunWith(MockitoJUnitRunner.class)
@TestPropertySource
public class DataTestRepoTest {
private static final String url = "http://localhost:8080/data/name";
@Mock
private DataTestRepo DataTestRepo;
RestTemplate restTemplate = new RestTemplate();
@Test
public void restTemplateHttpPost_success() throws URISyntaxException {
URI uri = new URI(url);
Set<String> mockData = Stream.of("A","B").collect(Collectors.toSet());
Map<String, String> body = new HashMap<>();
body.put("Name", "Aws");
JSONObject jsonObject = new JSONObject(body);
HttpEntity<String> request = new HttpEntity<>(jsonObject.toString(), null);
ResponseEntity<String> result = restTemplate.exchange(uri, HttpMethod.POST,
new HttpEntity<>(request, DataTestRepo.getHttpHeaders()), String.class);
Assert.assertEquals(201, result.getStatusCodeValue());
}
}
【问题讨论】:
标签: java spring post mocking resttemplate