java - 如何为以下代码创建 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);
}
解决方案
@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
}
推荐阅读
- java - 从逗号分隔的整数的字符串数组映射的连续天数
- bash - docker:使用 -it /bin/bash 时来自守护进程的错误响应
- kubernetes - 流量的重新路由不适用于入口控制器。我觉得我误解了重写注释?
- flutter - 带有来自 Firestore 的数据的条件语句
- sql - Django JSONField,我如何获取存储在列表中的值的出现次数
- c++ - 函数 length() 可以带参数吗?
- c# - 如何在 ASP.NET Core 3 中处理从 400 到 500 的异常
- bash - 如何使用 execv 合并命令?例如。ls | grep -c "表达式"
- java - Java OpenJDK 中缺少 JavaFX
- php - 当我尝试在我的项目 laravel 6.x 上使用 redis 时,它会显示此错误消息