【问题标题】:Branch coverage in a java super class which is an abstract class作为抽象类的 java 超类中的分支覆盖
【发布时间】:2017-05-26 12:08:19
【问题描述】:

如何解决在抽象类的具体方法中反映的 cobertura 分支覆盖问题。

在下面的 sn-p 中,抽象类 Currency 的 equals 方法包含一个检查变量 SID 和 Ab 的部分,该变量位于条件之后 如果(getClass()!= obj.getClass())。 这部分永远不会被覆盖

     @Override      
     public boolean equals(Object obj) {
         if (this == obj)
             return true;
         if (obj == null)
             return false;
         if (getClass() != obj.getClass())
             return false;
         if (getClass() != obj.getClass())
             return false;
         final Currency other = (Currency) obj;
         if (this.getAb() == null) {
             if (other.Ab() != null)
                 return false;
         } else if (!this.getAb().equals(other.getAb()))
             return false;
         if (this.getSID() < 1 || (this.getSID() != other.getSID()))
             return false;
         return true;
         }

我尝试使用以下方法在测试类中覆盖这些变量,但仍然没有被覆盖:

测试类:

    Currency currency = new Currency() {
        @Override
        public boolean equals(Object obj) {
            return super.equals(obj);
        }
    };

   Currency currency1 = new Currency() {
        @Override
        public boolean equals(Object obj) {
            return super.equals(obj);
        }
    };      

    currency.setAb("SE3421");
    currency1.setAb("SE3421");
    assertFalse(currency.equals(currency1));
    assertTrue((currency1.getAb()).equals(currency.getAb()));   

感谢任何帮助。

【问题讨论】:

    标签: java unit-testing sonarqube cobertura


    【解决方案1】:

    我会添加一个新的测试方法,比如这个。

    @test
    public void test_equals() {
      Currency currency = new Currency() {    };
      assertFalse(currency.equals(new String()));
    }
    

    另一条评论:您也应该真正实现 hashCode 方法。

    在 hashCode() 中它说:如果两个对象根据 equals(Object) 方法相等,则对两个对象中的每一个调用 hashCode 方法必须产生相同的整数结果。如果你只覆盖 equals() 而不是 hashCode() 你的类违反了这个合同

    【讨论】:

    • 因为这个合同,OP 可能会在一个超类中审查equals 的(通用)实现......
    • mockito 在这种情况下会有所帮助,还是可以通过覆盖测试类中编写的货币实现中的 hashcode 方法来完成?
    猜你喜欢
    • 1970-01-01
    • 2016-01-02
    • 2013-02-25
    • 1970-01-01
    • 1970-01-01
    • 2012-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多