在测试中排除应用程序事件侦听器?

Aks*_*r T 5 events junit caching spring-boot

我在解决这个问题时遇到了问题。

我在应用程序中使用缓存,并使用监听器在应用程序启动时加载它。

@EventListener(ApplicationReadyEvent.class)
public void LoadCache() {
    refreshCache();
}

public void refreshCache() {
    clearCache(); // clears cache if present
    populateCache();
}
public void populateCache() {
    // dao call to get values to be populated in cache
    List<Game> games = gamesDao.findAllGames();
    // some method to populate these games in cache.
}
Run Code Online (Sandbox Code Playgroud)

当我运行应用程序时,这一切正常。然而,当我运行测试用例时,会出现问题,LoadCache()在运行安装程序时会调用该测试用例。我不希望在执行测试时运行它。

这是一个示例测试用例

@RunWith(SpringRunner.class)
@SpringBootTest(classes = GameServiceApplication.class)
public class GameEngineTest {
    @Test
    public void testSomeMethod() {
        // some logic
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 2

如果您可以将 EventListener 移至单独的类中并将其作为 Bean,那么您可以在测试中使用 mockBean 来模拟真实的实现。

@Component
public class Listener {

    @Autowired
    private CacheService cacheService;

    @EventListener(ApplicationReadyEvent.class)
    public void LoadCache() {
        cacheService.refreshCache();
    }
}

@Service
public class CacheService {

    ...

    public void refreshCache() {
        ..
    }

    public void populateCache() {
        ..
    }   
}


@RunWith(SpringRunner.class)
@SpringBootTest
public class CacheServiceTest {

    @MockBean
    private Listener listener;

    @Test
    public void test() {
        // now the listener mocked and an event not received.
    }
}
Run Code Online (Sandbox Code Playgroud)

或者您可以使用配置文件仅在生产模式下运行此侦听器。