要測試Java中的equals
方法是否正確工作,您可以創建一個測試類并編寫一些測試用例來驗證該方法的行為
equals
方法。這是一個簡單的示例:public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
Person person = (Person) obj;
return age == person.age && Objects.equals(name, person.name);
}
}
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class PersonTest {
// 測試用例將在這里編寫
}
equals
方法的行為。@Test
void testEquals_SameObject() {
Person person1 = new Person("Alice", 30);
assertTrue(person1.equals(person1));
}
@Test
void testEquals_Null() {
Person person1 = new Person("Alice", 30);
assertFalse(person1.equals(null));
}
@Test
void testEquals_DifferentClass() {
Person person1 = new Person("Alice", 30);
String notAPerson = "Not a person";
assertFalse(person1.equals(notAPerson));
}
@Test
void testEquals_EqualPersons() {
Person person1 = new Person("Alice", 30);
Person person2 = new Person("Alice", 30);
assertTrue(person1.equals(person2));
}
@Test
void testEquals_NotEqualPersons() {
Person person1 = new Person("Alice", 30);
Person person2 = new Person("Bob", 25);
assertFalse(person1.equals(person2));
}
equals
方法按預期工作。注意:在實際項目中,您可能需要使用更復雜的測試框架(如Mockito或PowerMock)或使用參數化測試來減少重復代碼。但是,這個簡單的示例應該足以幫助您開始測試equals
方法。