模拟服务测试和日期时间随机失败

时间:2016-08-01 02:07:35

标签: java unit-testing datetime mockito powermockito

我正在进行一项在Bamboo上随机失败的测试。这个比例就像每10个版本中的1个失败一样。它在我当地的环境中从未失败。

此处我的服务已简化:

public final class TripAdvisorSwitchServiceImpl implements TripAdvisorSwitchService{

    private FfxProperties ffxProperties = FfxProperties.getInstance();

    private DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZ");

    @Reference
    private DateTimeService dateTimeService;

    private static boolean forceEnable;

    @Override
    public boolean isEnabled() {
        if (forceEnable) {
            return true;
        }

        String endDateStr = ffxProperties.get("tripadvisor.endDate");
        DateTime endDate;
        try {
            endDate = dateTimeFormatter.parseDateTime(endDateStr);
        } catch (IllegalArgumentException e) {
            LOG.error("Date format is wrong: {}", endDateStr);
            return true;
        }

        return dateTimeService.getCurrentDateTime().isBefore(endDate);
    }
}

这是我随机的失败测试:

@RunWith(PowerMockRunner.class)
@PrepareForTest(FfxProperties.class)
public class TripAdvisorSwitchServiceImplTest {

    private DateTimeZone utcTimezone = DateTimeZone.forTimeZone(TimeZone.getTimeZone("UTC"));

    @InjectMocks
    private TripAdvisorSwitchServiceImpl tripAdvisorSwitchService;

    @Mock
    FfxProperties ffxProperties;

    @Mock
    DateTimeService dateTimeService;

    @Before
    public void setup() throws IllegalAccessException {
        MockitoAnnotations.initMocks(this);
        mockStatic(FfxProperties.class);
        when(FfxProperties.getInstance()).thenReturn(ffxProperties);
    }

    @Test
    public void tripAdvisorShouldBeDisabledAfterTheEndDate() {
        when(ffxProperties.get("tripadvisor.endDate")).thenReturn("2010-09-14T14:00:00+0000");
        when(dateTimeService.getCurrentDateTime()).thenReturn(new DateTime(2016, 9, 14, 14, 1, 0, 0, utcTimezone));

        assertFalse("It should be disabled", tripAdvisorSwitchService.isEnabled());
    }
}

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:0)

它如何完全失败?在这个例子中,我没有看到正在注入的ffxProperties或dateTimeService,我可以确认这只是因为你在发布时简化了问题吗?

我还没有看到问题,但通常情况下,当我的盒子上的某些东西总是成功但是在构建盒上定期失败时,时间问题就出现了,我确实看到了时间,所以我很怀疑那。

但到目前为止,我的第一个猜测是这些字段没有被注入,或者以某种方式以某种方式返回当前时间 - 如果它足够快可能两个调用返回相同的日期时间而失败?您可以通过设置断点或记录并确认日期时间是您认为的那样来测试。

答案 1 :(得分:0)

此问题是由于使用静态字段forceEnable(由其他测试操作)以及并行执行Bamboo测试而引起的。

相关问题