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



我在弄清楚这一点时遇到了问题。

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

@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.
}

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

这是一个样本测试用例

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

如果您可以将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.
}
}

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

最新更新