我试图覆盖90%以上,实际上正在努力覆盖100%。
有了所有这些,我得到了 75% 到 80% 这里只讨论 equals 方法。我错过了什么吗?
找到一篇关于 EqualsVerifier 的文章,但不明白如何在我的代码中使用它。 https://jqno.nl/equalsverifier/errormessages/coverage-is-not-100-percent/
@Data
public class Person {
private String name;
private int age;
}
我的测试代码
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class PersonTest {
@Test
public void testEquals_PositiveScenario() {
// Create two Person objects with the same attributes
Person person1 = new Person("John", 30);
Person person2 = new Person("John", 30);
// Check if they are equal using the equals() method
assertTrue(person1.equals(person2));
}
@Test
public void testEquals_NegativeScenario_DifferentName() {
// Create two Person objects with different names
Person person1 = new Person("John", 30);
Person person2 = new Person("Alice", 30);
// Check if they are not equal using the equals() method
assertFalse(person1.equals(person2));
}
@Test
public void testEquals_NegativeScenario_DifferentAge() {
// Create two Person objects with different ages
Person person1 = new Person("John", 30);
Person person2 = new Person("John", 25);
// Check if they are not equal using the equals() method
assertFalse(person1.equals(person2));
}
@Test
public void testEquals_NegativeScenario_NullObject() {
// Create a Person object
Person person = new Person("John", 30);
// Check if it is not equal to null using the equals() method
assertFalse(person.equals(null));
}
@Test
public void testEquals_NegativeScenario_DifferentClass() {
// Create a Person object
Person person = new Person("John", 30);
// Check if it is not equal to an object of a different class using the equals() method
assertFalse(person.equals(new Object()));
}
}
当您构建项目时,您将有一个输出目录,其中包含您的代码+由 Lombok 等工具添加的生成代码。找到您的
Person.class
文件并查看 lombok 添加的代码。然后您可以相应地更新您的测试。
然而...追求 100% 的代码覆盖率通常不是一个好主意。它可能会产生一种错误的安全感(代码覆盖率并不总是意味着那么多),并导致您编写一堆无用的测试。 请记住,每项测试都会增加应用程序的拥有成本。您真的需要测试 Java 语言吗(例如 getters/setters、生成的代码等)。
Lombok 可以为其添加的代码添加
@Generated
注释,大多数代码扫描器不会将其包含在报告中(配置为 `lombok.addLombokGenerateAnnotation = true)。这样您就可以测试重要部分,并排除其余部分。
祝你好运!