【发布时间】:2016-05-12 13:28:12
【问题描述】:
我有一个简单的 java 程序,需要测试两个 POJO 元素列表是否相等。
public void i_have_following(List<Post> myPost) throws Throwable {
//retrieve list of element from rest end point
String url = "http://jsonplaceholder.typicode.com/posts/";
RestTemplate restTemplate = new RestTemplate();
ParameterizedTypeReference<List<Post>> responseType = new ParameterizedTypeReference<List<Post>>() {
};
ResponseEntity<List<Post>> responseEntity = restTemplate.exchange(url,
HttpMethod.GET, null, responseType);
List<Post> allPosts = responseEntity.getBody();
//get size=1 sublist of it and compare with expected local value
List<Post> firstPost = allPosts.subList(0, 1);
System.out.println("size of firstPost = " + firstPost.size());
System.out.println("size of myPost = " + myPost.size());
Assert.assertEquals(firstPost.size(), myPost.size());
Assert.assertEquals(firstPost.get(0).getUserId(), myPost.get(0)
.getUserId());
Assert.assertEquals(firstPost.get(0).getId(), myPost.get(0).getId());
Assert.assertEquals(firstPost.get(0).getTitle(), myPost.get(0)
.getTitle());
Assert.assertEquals(firstPost.get(0).getBody(), myPost.get(0).getBody());
Assert.assertTrue(firstPost.equals(myPost)); //FAIL!!
Assert.assertTrue(firstPost.containsAll(myPost)); //FAIL!!
}
控制台输出为:
size of firstPost = 1
size of myPost = 1
java.lang.AssertionError
at org.junit.Assert.fail(Assert.java:86)
at org.junit.Assert.assertTrue(Assert.java:41)
at org.junit.Assert.assertTrue(Assert.java:52)
“POST”元素只是一个简单的 POJO 元素:
public class Post {
private Integer userId;
private Integer id;
private String title;
private String body;
/**
*
* @return The userId
*/
public Integer getUserId() {
return userId;
}
/**
*
* @param userId
* The userId
*/
public void setUserId(Integer userId) {
this.userId = userId;
}
/**
*
* @return The id
*/
public Integer getId() {
return id;
}
/**
*
* @param id
* The id
*/
public void setId(Integer id) {
this.id = id;
}
/**
*
* @return The title
*/
public String getTitle() {
return title;
}
/**
*
* @param title
* The title
*/
public void setTitle(String title) {
this.title = title;
}
/**
*
* @return The body
*/
public String getBody() {
return body;
}
/**
*
* @param body
* The body
*/
public void setBody(String body) {
this.body = body;
}
}
从打印输出和断言可以看出,这两个列表具有相同的 size=1,并且它们的唯一列表元素具有相同的值(最后两个之前的所有断言都是 TRUE)。
我真的很困惑为什么最后两个断言会失败。我假设 equals() 和 containsAll() 是用于列表比较的常用 api,我正确使用它们。
谁能告诉我这里缺少什么?
欣赏它。
【问题讨论】:
-
这些 cmets 值得登上 4chan 的首页...