我可以测试代码,但是代码覆盖范围不包括第二种开关情况。
请参考下面的代码。
{ @PersistenceContext
EntityManager manager;
@Autowired
TurbineRepository turbineRepository;
@Autowired
WorkRepository workRepository;
public Dropdown getDropdown(String type) {
Dropdown dropdownDTO = new Dropdown();
switch(type) {
case "turbine":
List<String> turbinesList = turbineRepository.listOfTurbines();
dropdownDTO.setTurbinesList(turbinesList);
break;
case "wocreate":
List<String> turbineList = turbineRepository.listOfTurbines();
dropdownDTO.setTurbinesList(turbineList);
List<ParamsProjection> params = workRepository.findBy();
Map<String, List<ParamsProjection>> result = params.stream()
.collect(Collectors.groupingBy(ParamsProjection::getType));
dropdownDTO.setParams(result);
default:
}
return dropdownDTO;
}
下面是我的测试代码。
{
@InjectMocks
private Services service;
@Mock
private WorkRepository workRepo;
@Mock
private TurbineRepository turbineRepo;
@Mock
private ParamsProjection paramProject1;
@Test
public void getDropDown() {
Dropdown dto = new Dropdown();
List<String> turbineList = new ArrayList<String>();
String type = "turbine";
switch(type) {
case "turbine" :
Mockito.when(turbineRepo.listOfTurbines()).thenReturn(turbineList);
dto.setTurbinesList(turbineList);
assertNotNull(dto);
break;
case "wocreate":
DropdownDTO dto2 = new DropdownDTO();
Mockito.when(turbineRepo.listOfTurbines()).thenReturn(turbineList);
dto2.setTurbinesList(turbineList);
List<ParamsProjection> param = new ArrayList<ParamsProjection>();
Mockito.when(workRepo.findBy()).thenReturn(param);
Map<String, List<ParamsProjection>> result = param.stream()
.collect(Collectors.groupingBy(ParamsProjection::getType));
dto2.setParams(result);
assertNotNull(dto2);
break;
}
assertNotNull(service.getDropdown("turbine"));
}
因为我已经声明了一个带有用于测试的值的字符串变量,所以我无法涵盖第二个switch语句。我已经尝试过if-else情况,但是发生相同的问题。还有其他方法可以做到这一点吗?
您type
始终是"turbine"
,因此只测试了这种情况。进行两种不同的测试是有意义的,每种类型一种:
@Test
public void getDropDownTurbine() {
Dropdown dto = new Dropdown();
List<String> turbineList = new ArrayList<String>();
String type = "turbine";
Mockito.when(turbineRepo.listOfTurbines()).thenReturn(turbineList);
dto.setTurbinesList(turbineList);
assertNotNull(dto);
assertNotNull(service.getDropdown("turbine"));
}
@Test
public void getDropDown() {
List<String> turbineList = new ArrayList<String>();
String type = "wocreate";
DropdownDTO dto2 = new DropdownDTO();
Mockito.when(turbineRepo.listOfTurbines()).thenReturn(turbineList);
dto2.setTurbinesList(turbineList);
List<ParamsProjection> param = new ArrayList<ParamsProjection>();
Mockito.when(workRepo.findBy()).thenReturn(param);
Map<String, List<ParamsProjection>> result = param.stream()
.collect(Collectors.groupingBy(ParamsProjection::getType));
dto2.setParams(result);
assertNotNull(dto2);
assertNotNull(service.getDropdown("wocreate"));
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句