在练习重写equals方法时写测试方法遇到这个问题
先放报错代码:
public class Order {
int orderId;
String orderName;
public int getOrderId() {
return orderId;
}
public void setOrderId(int orderId) {
this.orderId = orderId;
}
public String getOrderName() {
return orderName;
}
public void setOrderName(String orderName) {
this.orderName = orderName;
}
public Order(int orderId, String orderName) {
this.orderId = orderId;
this.orderName = orderName;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (obj instanceof Order order) {
return orderId == order.orderId && orderName.equals(order.orderName);
}
return false;
}
@Test
public void test2() {
Order order1 = new Order(1,"2023-3-16购买");
Order order2 = new Order(1,"2023-3-16购买");
System.out.println(order1.equals(order2) ? "相同" : "不同");
}
}
这也是我第一次遇到这个错误“测试类里面只允许存在一个无参构造方法”。
起因:为偷懒、直接在类里面写测试方法。然后实例化类的时候使用了带参的构造方法。
结果:报错!
解决方法:删掉带参的构造方法,实例化时用set()方法给属性赋值。
public class Order {
int orderId;
String orderName;
public int getOrderId() {
return orderId;
}
public void setOrderId(int orderId) {
this.orderId = orderId;
}
public String getOrderName() {
return orderName;
}
public void setOrderName(String orderName) {
this.orderName = orderName;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (obj instanceof Order order) {
return orderId == order.orderId && orderName.equals(order.orderName);
}
return false;
}
@Test
public void test2() {
Order order1 = new Order();
order1.setOrderName("2023-03-13下单");
order1.setOrderId(1);
Order order2 = new Order();
order2.setOrderId(2);
order2.setOrderName("2023-03-13下单");
System.out.println(order1.equals(order2) ? "相同订单" : "不同订单");
}
}
解决!!