使用TestRestTemplate传递查询参数

6

您好,我正在使用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);
}

当我调试代码时,每当请求到达端点时,我尝试通过测试发送的参数以某种方式为空,因此过滤器为null,而Pageable则使用默认值,因为它将其设置为page=0size=20。我尝试使用TestRestTemplate类中的.exchange(...).getForEntity(...).getForObject(...)方法,但似乎都无法使用查询参数,请问是否有人能帮助我并告诉我可能做错了什么,真的非常感谢!

2个回答

9

您的问题似乎是在URL中没有包含参数。应该像这样:

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

请在以下链接找到一些例子,以便帮助您。

{btsdaf} - Tuco
1
{btsdaf} - Tuco
{btsdaf} - ervidio

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接