是否可以将标头设置为getForEntity方法的一部分,还是应该使用exchange?我试图将oauth标头设置为getForEntity调用的一部分。
答案 0 :(得分:14)
您可以使用ResponseEntity<YourResponseObj> entity = new TestRestTemplate().exchange(
"http://localhost:" + port + "/youruri", HttpMethod.GET, new HttpEntity<Object>(headers),
YourResponseObj.class);
:
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class ReferenceTablesControllerTests {
@LocalServerPort
private int port;
@Test
public void getXxxx() throws Exception {
MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
headers.add("Content-Type", "application/json");
headers.add("Authorization", "tokenxxx");
ResponseEntity<YourResponseObj> entity = new TestRestTemplate().exchange(
"http://localhost:" + port + "/youruri", HttpMethod.GET, new HttpEntity<Object>(headers),
YourResponseObj.class);
Assert.assertEquals(HttpStatus.OK, entity.getStatusCode());
Assert.assertEquals("foo", entity.getBody().getFoo());
}
}
Full Junit样本:
{{1}}