我有一个abstract class Printers
,我只想测试其equals
方法,但是当我在Printers
中创建两个PrintersTest
时,我无法对其进行实例化。
这是PrintersTest
:
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
class PrintersTest {
@Test
void testEqualsObject() {
Printers a = new Printers("BW_LASER HP", "Laserjet 1230", "25", "180 euros");
Printers b = new Printers("BW_LASER HP", "Laserjet 1230", "25", "180 euros");
assertEquals(a,b);
}
}
这是Printers
类:
import java.util.Objects;
public abstract class Printers {
protected String brand;
protected String model;
protected String pages;
protected String price;
public Printers(String brand, String model, String pages, String price) {
super();
this.brand = brand;
this.model = model;
this.pages = pages;
this.price = price;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof Printers)) {
return false;
}
Printers other = (Printers) obj;
return Objects.equals(brand, other.brand) && Objects.equals(model, other.model)
&& Objects.equals(pages, other.pages) && Objects.equals(price, other.price);
}
}
非常感谢您的帮助。
答案 0 :(得分:1)
您需要从打印机扩展另一个类(可能已经拥有),例如某种打印机或其他类型,然后在测试类中,基于该类创建一个新的打印机,如下所示:
@Test
void testEqualsObject() {
Printers a = new Bw("BW_LASER HP", "Laserjet 1230", "25", "180 euros");
Printers b = new Bw("BW_LASER HP", "Laserjet 1230", "25", "180 euros");
assertEquals(a,b);
}
这将解决您的问题,因为您无需实例化打印机。