Java - 使用 Matchers 对 void 方法进行单元测试



我正在尝试测试如下所示的 void 方法:

@Override
    public void onApplicationEvent(ApplicationEvent myEvent) {
        if (myEvent instanceof ApplicationEnvironmentPreparedEvent) {
            ConfigurableEnvironment myEnv= ((ApplicationEnvironmentPreparedEvent) myEvent).getEnvironment();
            setSystemVariables(myEnv);
        }
    }

我正在使用匹配器,这是单元测试(显然没有测试任何东西)

@Test
    public void testOnApplicationEvent() {
        loggingListener.onApplicationEvent(any(ApplicationEnvironmentPreparedEvent.class));
    }

两个问题:1. 我从构建中得到的错误是"匹配器使用无效",并且测试在我的 Jenkins 构建中没有通过(但在想法 IDE 中通过)2. 如何测试这些方法以使测试覆盖率保持在所需水平

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);
}

请注意,这不是可编译的代码,因为我不知道您的完整生产代码,因此请将其视为将其应用于您的真实代码并进行相应修改的想法。

相关内容

  • 没有找到相关文章