如何在代码覆盖率中覆盖equals方法 [英] How to cover equals method in code coverage

查看:387
本文介绍了如何在代码覆盖率中覆盖equals方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

新的代码覆盖范围,希望获得一些见解...

New to code coverage, would like to have some insights...

     public boolean equals(Object obj) {
    if (this == obj) {
        return true;
    }
    if (obj == null) {
        return false;
    }
    if (getClass() != obj.getClass()) {
        return false;
    }
    final Person other = (Person) obj;
    if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) {
        return false;
    }
    if ((this.email == null) ? (other.email != null) : !this.email.equals(other.email)) {
        return false;
    }
    if (this.age != other.age && (this.age == null || !this.age.equals(other.age))) {
        return false;
    }
    return true;
}

我如何在jcoco代码覆盖率中对此进行介绍.

How do I cover this in jcoco code coverage.

推荐答案

要对该类进行100%测试,您应该为每个if?:运算符创建一个测试.代码的每个部分都应进行测试.例如,第一个if (this == obj),您应该在哪里进行测试

To have this class 100% tested you should create a test for every if and ?: operator. Every part of the code should be tested. For instance, the first if (this == obj), you should have a test where you do

@Test
public void testEqualsSameObj() {
    MyClass sut = new MyClass(); // sut == system under test
    assertTrue (sut.equals(sut));
}

现在进行下一个传递null的测试:

And now make the next test for passing null:

@Test
public void testEqualsNull() {
    MyClass sut = new MyClass(); // sut == system under test
    assertFalse (sut.equals(null));
}

并继续下一个条件,直到覆盖代码中的所有分支.

And continue with the next condition, until you cover all branches in the code.

您可以从方法中获取sut并将其作为成员变量存储在测试类中.

You can take the sut from the method and store it in the test class as a member variable.

这篇关于如何在代码覆盖率中覆盖equals方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆