泽西客户单元测试

时间:2014-03-23 10:02:16

标签: java junit jersey jersey-client

我已经设置了Jersey资源,它可以在浏览器中完美地返回List。但我不能让它在我的单元测试中运行。我收到错误消息:

A message body writer for Java class java.util.ArrayList, and Java type java.util.List<at.sunfinder.dto.Location>, and MIME media type application/json was not found

我将我的课程附加在以下

资源:

@GET
    @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
    public List<Location> getWeather(@QueryParam("latitude") double latitude, @QueryParam("longitude") double longitude,
            @QueryParam("radius") int radius, @QueryParam("countryCode") String countryCode /* Datum */) {

        setWeatherController(new WeatherControllerImpl());      
        return weatherController.getWeather(latitude, longitude, radius, countryCode);
    }

位置DTO:

@XmlRootElement
public class Location {

    private String location;
    private double latitude;
    private double longitude;
    private Weather weather;

    @XmlTransient
    private Date lastUpdate;

    public Location(){}

    public Location(double latitude, double longitude, String location, Weather weather, Date lastUpdate){
        this.latitude = latitude;
        this.longitude = longitude;
        this.location = location;
        this.weather = weather;
        this.lastUpdate = lastUpdate;
    }

    @XmlElement(name="location")
    public String getLocation() {
        return location;
    }

    @XmlElement(name="latitude")
    public double getLatitude() {
        return latitude;
    }

    @XmlElement(name="longitude")
    public double getLongitude() {
        return longitude;
    }

    @XmlElement(name="weather")
    public Weather getWeather(){
        return weather;
    }   
}

我的单元测试:

@Test
    public void testGetWeather(){       

        Client client = Client.create();         


        WebResource webResource = client.resource(url); 
        ClientResponse response = webResource.accept("application/json").get(ClientResponse.class);

        List<Location> locations = null;

        if(response.getClientResponseStatus() == ClientResponse.Status.OK){
            locations = response.getEntity(new GenericType<List<Location>>(){});
        }

        assertTrue(locations.size()> 0);
    }

我的pom xml具有以下依赖项:                              com.sun.jersey                 球衣服务器                 1.18.1             

        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-servlet</artifactId>
            <version>1.18.1</version>
        </dependency>

        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-client</artifactId>
            <version>1.18.1</version>
        </dependency>

1 个答案:

答案 0 :(得分:0)

您的测试似乎是在请求 application / json 格式,但您的位置DTO无法解析它。尝试更改测试以请求 application / xml ,即:

ClientResponse response = webResource.accept("application/xml").get(ClientResponse.class);

或者,确保您的DTO也可以解析json(通过提供@JsonProperty注释)。