我正在尝试测试以下无效方法:
@Override
public void onApplicationEvent(ApplicationEvent myEvent) {
if (myEvent instanceof ApplicationEnvironmentPreparedEvent) {
ConfigurableEnvironment myEnv= ((ApplicationEnvironmentPreparedEvent) myEvent).getEnvironment();
setSystemVariables(myEnv);
}
}
我正在使用Matchers,这是单元测试(显然没有测试任何东西)
@Test
public void testOnApplicationEvent() {
loggingListener.onApplicationEvent(any(ApplicationEnvironmentPreparedEvent.class));
}
两个问题: 1.我从构建中得到的错误是“无效使用Matchers”,并且我的Jenkins构建中未通过测试(但在Idea IDE中通过了) 2.如何测试这些方法以将测试覆盖率保持在期望的水平
答案 0 :(得分:1)
1-此问题是因为any
的使用不正确。有关详细信息,请参见Mockito
指南。在我的示例下面,不使用any
,问题将消失。
2-为了涵盖if
的2个分支,我建议使用以下测试用例。
@Test
public void onApplicationEventShouldSetEnvironmentWhenApplicationEnvironmentPreparedEvent() {
ConfigurableEnvironment actualEnvironment = null;
// Given a listener with overridden setSystemVariables() to store passed env.
LoggingListener loggingListener = new LoggingListener() {
@Override
void setSystemVariables(ConfigurableEnvironment var){
actualEnvironment = var;
}
};
// Given some dummy environment which is delivered by an event.
ConfigurableEnvironment expectedEnvironment = new ConfigurableEnvironment();
// Given a mocked event with above dummy environment.
ApplicationEvent mockedEvent = Mockito(ApplicationEnvironmentPreparedEvent.class);
Mockito.when(mockedEvent.getEnvironment()).returns(expectedEnvironment);
// When call a method under test
loggingListener.onApplicationEvent(mockedEvent);
// Then make sure the given environment was passed and set correctly
assertSame(expectedEnvironment, actualEnvironment);
}
@Test
public void onApplicationEventShouldSkipNotApplicationEnvironmentPreparedEvent() {
// Given a listener with overridden setSystemVariables() to fail the test if called.
LoggingListener loggingListener = new LoggingListener() {
@Override
void setSystemVariables(ConfigurableEnvironment var){
fail("This method should not be called");
}
};
// Given a mocked other (not ApplicationEnvironmentPreparedEvent) event.
ApplicationEvent mockedEvent = Mockito(UnknownEvent.class);
// When call a method under test
loggingListener.onApplicationEvent(mockedEvent);
// Then make sure an environment was not asked at all.
Mockito.verify(mockedEvent.getEnvironment(), never);
}
请注意,这不是可编译的代码,因为我不知道您的完整生产代码,因此请将其作为一种想法,通过相应的修改将其应用于您的真实代码。