将查询参数传递给TestRestTemplate

时间:2017-10-23 14:58:02

标签: java spring-boot integration-testing

您好我使用TestRestTemplate为我的代码实现了一些集成测试,在尝试测试端点时,我找不到包含查询参数的方法。

以下是我尝试过的两种不同的测试:

@Test
@DisplayName("Test list all filtered by boolean field")
void testListAllBooleanFilter() {
    Map<String, String> params = new HashMap<>();
    params.put("page", "0");
    params.put("size", "5");
    params.put("filters", "active=true");
    ResponseEntity<AdminDTO[]> response = this.testRestTemplate.getForEntity("/api/v1/admin", AdminDTO[].class,
            params);
    assertThat(response.getBody()).isNotNull();
    assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
    assertThat(response.getBody()).hasSize(2);
    assertThat(response.getBody()[0].getActive()).isTrue();
    assertThat(response.getBody()[1].getActive()).isTrue();
}

@Test
@DisplayName("Test list all with empty result")
void testListAllEmptyResult() {
    HttpEntity<String> requestEntity = new HttpEntity<>(new HttpHeaders());
    Map<String, String> params = new HashMap<>();
    params.put("page", "0");
    params.put("size", "5");
    params.put("filters", "active=false");
    ResponseEntity<List> response = this.testRestTemplate.exchange("/api/v1/admin", HttpMethod.GET,
            requestEntity, List.class, params);
    assertThat(response.getBody()).isNotNull();
    assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
    assertThat(response.getBody()).isEmpty();
}

以下是我正在测试的控制器:

@GetMapping(value = "/admin", produces = "application/json")
public ResponseEntity listAll(String filters, Pageable pageable) {
    if(filters ==  null) {
        filters = "type=" + ADMIN.toString();
    } else {
        filters += ",type=" + ADMIN.toString();
    }
    Condition condition = filterMapService.mapFilterToCondition("user_account", filters);
    List<AdminDTO> adminAccounts = userAccountRepository.findAllByFilter(condition, pageable);
    if (adminAccounts.isEmpty()) {
        return new ResponseEntity<>(adminAccounts, HttpStatus.OK);
    }
    return new ResponseEntity<>(adminAccounts, HttpStatus.OK);
}

基本上当我调试代码时,每当请求到达端点时,我尝试通过测试发送的参数都是空的,因此过滤器为空并且Pageable我猜测使用默认值,因为它设置了它们到page=0size=20。我尝试使用.exchange(...)类中的.getForEntity(...).getForObject(...)TestRestTemplate方法,但似乎没有一个与查询参数一起使用,有人可以帮我解决问题并告诉我什么我可能做错了,我真的很感激!

2 个答案:

答案 0 :(得分:3)

看起来您的问题是您没有在您的网址中包含参数。它应该是这样的:

    /api/v1/admin?page={page}&size={size}&filters={filters} 

请在以下link中找到一些示例,以防它可以帮助您

答案 1 :(得分:0)

我个人认为这应该是这样的: I am using TestRestTemplate to Test with @RequestParam value how to execute

如果有人正在寻找正确的答案,我将在此处留下链接