我有一个如下的休息端点:
@PostMapping(value = "/customers/{customerId}")
public SomeResponse manageCustomers(@PathVariable String customerId){
...
}
此端点从一个系统中为给定的customerId选择客户数据,并将其保存在另一系统中。因此,它不需要任何请求正文。
我需要为此编写一个集成测试。当我为此使用testRestTemplate时,我找不到可以将requestEntity传递为null的足够好的方法。每当我这样做时,我都会收到一个异常消息,说“ uriTemplate不能为null”。
我试图使用'postForObject','exchange'方法,但是不起作用。有什么想法吗?
下面是我的IT:
@SpringBootTest(webEnvironmentSpringBootTest.WebEnvironment.RANDOM_PORT)
@DirtiesContext
@ActiveProfiles("test")
class CustomerIT extends Specification{
@LocalServerPort
private int port;
@Autowired
private TestRestTemplate restTemplate
def "should get customer from first system and save in second system"() {
given:
def customerUrl = new URI("http://localhost:" + port + "/customers/1234")
def expected = new SomeObject(1)
when:
def someObject =
restTemplate.postForEntity(customerUrl, null, SomeObject.class)
then:
someObject != null
someObject == expected
}
}
答案 0 :(得分:0)
使用postForEntity(url, null, ResponseType.class)
对我有用。
除了responseType之外,我的后映射等于您。我仅以Map
为例
@PostMapping(value = "/customers/{customerId}")
public Map<String, String> manageCustomers(@PathVariable String customerId){
return new HashMap<String, String>(){{ put("customerId", customerId); }};
}
测试以验证其是否有效
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class CustomerControllerTest {
@LocalServerPort
private int port;
private final TestRestTemplate testRestTemplate = new TestRestTemplate();
@Test
public void postEmptyBodyShouldReturn200OK() {
String customerId = "123";
ResponseEntity responseEntity = testRestTemplate
.postForEntity(format("http://localhost:%s/ping/customers/%s", port, customerId), null, Map.class);
assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(responseEntity.getHeaders().getContentType()).isEqualTo(MediaType.APPLICATION_JSON_UTF8);
assertThat(responseEntity.getBody()).isNotNull();
assertThat(((LinkedHashMap) responseEntity.getBody()).size()).isEqualTo(1);
assertThat(((LinkedHashMap) responseEntity.getBody()).get("customerId")).isEqualTo(customerId);
}
}
在Maven中运行此测试
$ mvn -Dtest=CustomerControllerTest test
(...removed unnecessary output...)
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 4.137 s - in com.ins.example.demo.rest.CustomerControllerTest
10:04:54.683 [Thread-3] INFO o.s.s.c.ThreadPoolTaskExecutor - Shutting down ExecutorService 'applicationTaskExecutor'
[INFO]
[INFO] Results:
[INFO]
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 6.940 s
[INFO] Finished at: 2019-04-07T10:04:55+02:00
[INFO] ------------------------------------------------------------------------