junit org.springframework.web.client.RestClientException:提取类型和内容类型[application/json;字符集=utf-8]

yrdbyhpb  于 2022-11-11  发布在  Spring
关注(0)|答案(1)|浏览(160)

我不知道是什么问题。我正在使用postgre DB。当我运行GET方法的测试时,出现了错误,第二天我无法解决它。
这是我的Entity类

import lombok.*;
import lombok.experimental.FieldDefaults;

import javax.persistence.*;

@Entity
@Table(name = "cities_catalog")
@FieldDefaults(level = AccessLevel.PRIVATE)
@Data
@NoArgsConstructor
public class PostgreCity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    Integer id;

    @Column(name = "name")
    String name;

    public PostgreCity(String name) {
        this.name = name;
    }
}

这是我的Repository类

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

    @Repository
    public interface CityRepository extends JpaRepository<PostgreCity, Integer> {
    }

下面是我的Controller类

import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.experimental.FieldDefaults;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@AllArgsConstructor
@FieldDefaults(makeFinal = true, level = AccessLevel.PRIVATE)
public class CityPostController {

    @Autowired
    CityRepository cityRepository;

    @GetMapping(value = "/get")
    public List<PostgreCity> get(){
        List<PostgreCity> list = this.cityRepository.findAll();
        return list;
    }
}

这是我的Junit测试类

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

import java.util.HashMap;

import static org.junit.jupiter.api.Assertions.*;

class CityPostControllerTest extends RequestService {

    @Autowired
    CityRepository cityRepositoryp;
    Integer id;

    @BeforeEach
    void setUp() {
    }

    @AfterEach
    void tearDown() {
    }

    @Test
    void get() {
        ResponseEntity<PostgreCity> responseEntity = this.get(PostgreCity.class);
        assertNotNull(responseEntity);
        assertEquals(HttpStatus.OK.value(), responseEntity.getStatusCodeValue());
    }

    @Override
    public String getPath() {
        return "/get";
    }
}

这是我的RequestService类

import io.egrow.eugene.insurance.InsuranceApplicationTests;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.*;

public abstract class RequestService extends InsuranceApplicationTests {

    @Autowired
    TestRestTemplate testRestTemplate;

    public <T> ResponseEntity<T> patchNoAuth(String payload, Class<T> tClass) {

        HttpHeaders headers = getHeaderWithoutAuthentication();
        HttpEntity<String> entity = new HttpEntity<>(payload, headers);

        return testRestTemplate.exchange(this.getPath(), HttpMethod.PATCH, entity, tClass);
    }

    public <T> ResponseEntity<T> get(Class<T> tClass) {

        return testRestTemplate.getForEntity(this.getPath(), tClass);
    }

    private HttpHeaders getHeaderWithoutAuthentication() {

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        return headers;
    }

    public abstract String getPath();
}

下面是我运行测试时错误消息

org.springframework.web.client.RestClientException: Error while extracting response for type [class io.egrow.eugene.insurance.boundary.databases.postgre.models.cities.PostgreCity] and content type [application/json;charset=utf-8]; nested exception is org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type `io.egrow.eugene.insurance.boundary.databases.postgre.models.cities.PostgreCity` from Array value (token `JsonToken.START_ARRAY`); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize value of type `io.egrow.eugene.insurance.boundary.databases.postgre.models.cities.PostgreCity` from Array value (token `JsonToken.START_ARRAY`)
 at [Source: (PushbackInputStream); line: 1, column: 1]
vjhs03f7

vjhs03f71#

问题就在这里:

ResponseEntity<PostgreCity> responseEntity = this.get(PostgreCity.class);

您需要一个实体,但在RestController中却有一个List:

@GetMapping(value = "/get")
public List<PostgreCity> get(){
    List<PostgreCity> list = this.cityRepository.findAll();
    return list;
}

要获取列表,可以使用ParameterizedTypeReference,如下所示:

ResponseEntity<List<PostgreCity>> responseEntity = 
  restTemplate.exchange(
    "/get",
    HttpMethod.GET,
    null,
    new ParameterizedTypeReference<List<PostgreCity>>() {}
  );
List<PostgreCity> postgreCities = responseEntity.getBody();

欲了解更多详情和参考可看一下本教程:
https://www.baeldung.com/spring-resttemplate-json-list

相关问题