我正在使用RestTemplate exchange HttpMethod.POST
方法发送到终结点。在我的测试文件中,我正在测试POST方法的success
。然而,在我目前的测试中,当发出POST请求时,我会得到401 Unauthorized error
。我需要帮助,以模拟API,同时在测试文件中进行POST请求
这是我的主文件
@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());
}
}
发布于 2020-01-27 02:14:11
您正在测试DataTestRepo类内部的逻辑,所以您不应该模拟它。RestTemplate是DataTestRepo中的一个依赖项,所以这正是您需要模拟的。一般来说,在你的测试中应该是这样的:
@InjectMocks
private DataTestRepo DataTestRepo;
@Mock
RestTemplate restTemplate;
此外,您还必须为模拟的依赖项提供返回值,如下所示:
Mockito.when(restTemplate.exchange(ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.any())).thenReturn(new ResponseEntity<>(yourExpectedDataHere, HttpStatus.OK));
enter code here
这只是一个简单的例子。一个不错的做法是检查传递给mock的参数是否与预期的一致。一种方法是用实际的预期数据替换ArgumentMatchers.any()。另一种方法是单独验证,如下所示:
Mockito.verify(restTemplate, Mockito.times(1)).exchange(ArgumentsMatchers.eq(yourExpectedDataHere), ArgumentsMatchers.eq(yourExpectedDataHere), ArgumentsMatchers.eq(yourExpectedDataHere), ArgumentsMatchers.eq(yourExpectedDataHere));
发布于 2020-01-27 03:01:09
这是关于这个主题的一个很棒的读物:https://reflectoring.io/spring-boot-web-controller-test/
https://stackoverflow.com/questions/59921249
复制相似问题