问题描述
我已经创建了一个类别Item,并且想要检查Item类的属性 “ firstName”是“ test”,“ lastName”是“ best”,但是我得到了 以下错误。我不是真的在这里出了什么问题。我有 毫无疑问是否需要执行以下操作。
谢谢。
这是我的代码:
@Test
public void testName(){
List<Item> items = new ArrayList<Item>();
Item item1= new Item("test","best");
Item item2= new Item("test","best");
Item item3= new Item("test","best");
items = Arrays.asList(item1,item2,item3);
assertthat(items,hasItems(allOf(Matchers.<Item>hasProperty("firstName",is("test")),Matchers.<Item>hasProperty("lastName",is("best")))));
}
课程项目{
public Item(){}
public Item(String firstName,String lastName){
this.firstName=firstName;
this.lastName=lastName;
}
private String firstName;
private String lastName;
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (obj.getClass() != this.getClass()) {
return false;
}
final Item other = (Item) obj;
if ((this.firstName == null) ? (other.firstName != null) : !this.firstName.equals(other.firstName)) {
return false;
}
return true;
}
@Override
public int hashCode() {
int hash = 3;
hash = 53 * hash + (this.firstName != null ? this.firstName.hashCode() : 0);
return hash;
}
}
我收到以下错误消息:
Expected: (a collection containing (hasProperty("firstName",is "test") and hasProperty("lastName",is "best")))
but: a collection containing (hasProperty("firstName",is "best")) hasProperty("firstName",is "test") No property "firstName",hasProperty("firstName",is "test") No property "firstName"
java.lang.AssertionError:
Expected: (a collection containing (hasProperty("firstName",is "test") No property "firstName"
at org.hamcrest.MatcherAssert.assertthat(MatcherAssert.java:20)
at org.hamcrest.MatcherAssert.assertthat(MatcherAssert.java:8)
at ImportTest.testName(ImportTest.java:220)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at
解决方法
我终于能够解决问题。问题是我有 在同一个类中创建了Item类,但它不是公开的。我创造了我的 Item类是一个单独的java类,并将其公开,并且对我有用。
public class Item {
public Item(){}
public Item(String firstName,String lastName){
this.firstName=firstName;
this.lastName=lastName;
}
private String firstName;
private String lastName;
// here is the public getter and setters
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (obj.getClass() != this.getClass()) {
return false;
}
final Item other = (Item) obj;
if ((this.firstName == null) ? (other.firstName != null) : !this.firstName.equals(other.firstName)) {
return false;
}
return true;
}
@Override
public int hashCode() {
int hash = 3;
hash = 53 * hash + (this.firstName != null ? this.firstName.hashCode() : 0);
return hash;
}
}