首页 > 解决方案 > 如何为以下代码创建 Junit 测试

问题描述

我能够获得第二个和第三个条件的承保范围,但无法获得最后一个和第一个条件的承保范围。

@Override public boolean equals(Object obj)
    {
        if(this == obj) {
            return true;
        }
        if(obj == null)
        {
            return false;
        }
        if(getClass() != obj.getClass()) {
            return false;
        }
        Rating other = (Rating) obj;
        boolean bool= score == other.score ;
        boolean bool2=Objects.equals(user, other.user);
        return bool&&bool2;
        
    }

下面是我的测试功能

    public void equalsTest_lastcondition() {
        Rating test=new Rating();
        
        Object obj2=testwa2;
        Rating other = (Rating) obj2;
        boolean bool=false;
        if(other.getScore()==testwa1.getScore())
        { bool=true;}
        boolean bool2 =Objects.equals(test.getUser(), other.getUser());
        assertEquals(true, bool && bool2);
    }   

标签: javaclasstestingjunitcode-coverage

解决方案


@Test
void equalsTest() {
   String score = 1;
   String user = "user";
   Rating rating = new Rating(score, user);
   assertTrue(rating.equals(rating)); // 1. if statement
   assertFalse(rating.equals(null)); // 2. if statement
   assertFalse(rating.equals(score)); // 3. if statement
   assertTrue(rating.equals(new Rating(score, user))); // other statements
}

更新:

String score = 1;
String user = "user";
Rating rating = new Rating(score, user);

@Test
void equalsShouldReturnTrueWhenComparingTheSameInstance() {
   assertTrue(rating.equals(rating)); // 1. if statement
} 

@Test
void equalsShouldReturnFalseWhenComparingTheNullValue() {
   assertFalse(rating.equals(null)); // 2. if statement
} 

@Test
void equalsShouldReturnFalseWhenComparingTheWrongType() {
   assertFalse(rating.equals(score)); // 3. if statement
} 

@Test
void equalsShouldReturnTrueWhenComparingNewInstanceWithSameValues() {
   assertTrue(rating.equals(new Rating(score, user))); // other statements
} 

推荐阅读