我有一个简单的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,我正确使用它们。
有人能给我一个暗示吗?
欣赏它。
答案 0 :(得分:2)
您比较2个相同的项目,您应该重写方法equals或使用Java Comparable Interface: https://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html
答案 1 :(得分:0)
Assert.assertEquals(firstPost.get(0), mytPost.get(0)
怎么样?我打赌你失败了...你的两个对象是不相等的。