简体   繁体   English

junit如何覆盖进入.CollectionUtils?isEmpty(disReadings)的if条件?

[英]How to junit cover and enter the if condition of !CollectionUtils.isEmpty(disReadings)?

I am learning junit and trying to junit test the class and I am not able to enter the if.CollectionUtils.isEmpty(disReadings) part of code through the code:我正在学习 junit 并尝试 junit 测试 class 并且我无法通过代码输入代码的if.CollectionUtils.isEmpty(disReadings)部分:

List<DisLRead> disLReadList = new ArrayList<>();
cHlDisList.forEach(dis -> {
List<Double> disReadingsL = disRepository
        .getReadsForDisId(dis.getDisId(), sDate, eDate);
        
if (!CollectionUtils.isEmpty(disReadingsL)) {
    double max = Round.RoundToTwoDecimal(
            disReadingsL.stream().mapToDouble(Double::doubleValue).max().getAsDouble());
    double min = Round.RoundToTwoDecimal(
            disReadingsL.stream().mapToDouble(Double::doubleValue).min().getAsDouble());
    double avg = Round.RoundToTwoDecimal(
            disReadingsL.stream().mapToDouble(Double::doubleValue).average().getAsDouble());
    DisLReading disLReading = new DisLReading();
    disLReading.setDisId(dis.getDisId());
    disLReading.setDisName(dis.getDisName());
    disLReading.setDisZ(dis.getDisZ());
    disLReading.setMax(max);
    disLReading.setMin(min);
    disLReading.setAverage(avg);
    disLReadList.add(disLReading);
}});

Update:更新:

Snippet of my test class:我的测试片段 class:

@Mock
DisRepository disRepository;

@Mock
Round round;
    List<DisLRead> disLReadList = new ArrayList<>();
    List<Double> disReadingsL = new ArrayList<>();
    disReadingsL.add(100.0000);
    disReadingsL.add(200.0000);
    when(disRepository.getReadsForDisId(anyInt(), anyString(), anyString()))
            .thenReturn(disReadingsL);
    assertNotNull(disReadingsL);
    assertEquals(!CollectionUtils.isEmpty(disReadingsL), true);
    

What am I doing wrong?我究竟做错了什么? how to enter the cover this part of code.如何进入覆盖这部分代码。 Thanks in advance!提前致谢!

You have more or less two options either use a mocking framework like mockito to create a mock object for "disRepository" it would look like this:您或多或少有两个选项,要么使用 mocking 框架,如 mockito 为“disRepository”创建模拟 object,它看起来像这样:

DisrepositoryClass disrepositoryMock = Mockito.mock(disrepository.class);
when(disrepositoryMock.getReadsForDisId(any(),any(),any()).thenReturn(List.of(Double.of(1d)));

Alternativly you create your own Mock object and provide it.或者,您可以创建自己的 Mock object 并提供它。

CollectionUtils.isEmpty() is a static method; CollectionUtils.isEmpty()是一个 static 方法; therefore, you have to use PowerMockito.因此,您必须使用 PowerMockito。

mockStatic(CollectionUtils.class);
given(CollectionUtils.isEmpty(anyList())).willReturn(true);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM