java - JUnits 检查 IF Else 条件
问题描述
代码文件 - originalFile.java
private setValueMethod(param1, param2) {
if (param1.getIsMale()) { // Its a boolean
param1.setCity(param2);
} else {
param1.setCity(param1.getOtherCity());
}
}
originalFileTest.java
@Test
public void testSetValueMethod() {
// some previous line setting mock value
when(param1.getIsMale()).then ('.... How to do what i have done in real code file...')
// How to implement if/else in JUnit tests
}
如何在 JUnits 中实现 if/else?
解决方案
您应该考虑编写两个测试。
@Test
public void shouldUseOtherCityOfParam1() {
ClassUnderTest classUnderTest = new ClassUnderTest();
Param1 param1 = mock(Param1.class);
Param2 param2 = mock(Param2.class);
Param2 otherCity = mock(Param2.class);
when(param1.getIsMale()).thenReturn(false);
when(param1.getOtherCity()).thenReturn(otherCity);
classUnderTest.setValueMethod(param1, param2);
verify(param1).setCity(eq(otherCity));
}
@Test
public void shouldUseParam2() {
ClassUnderTest classUnderTest = new ClassUnderTest();
Param1 param1 = mock(Param1.class);
Param2 param2 = mock(Param2.class);
when(param1.getIsMale()).thenReturn(true);
classUnderTest.setValueMethod(param1, param2);
verify(param1).setCity(eq(param2));
}
推荐阅读
- javascript - js循环递归
- python - 从具有多个值 Python 字典的每个键中获取具有最大计数的值
- python - python中每个模块的数量函数是否存在限制?
- swift - 无法从 Weather API 访问 JSON 数据
- python - 让两个 Django 项目共享同一个数据库有什么问题?
- java - try catch 块中的 Mockito Thread.class 异常不会提高覆盖率
- linux - swapon: /swapfile: swapon failed: Function not implemented 启用交换时
- flutter - Flutter中推送通知的最佳选择是什么?
- laravel - 在多个设备上测试应用程序而无需公开的最佳方式?
- python - 为什么我在 python 中收到此错误-> NameError: name 'FloatTensorType' is not defined