【问题标题】:Excluding Application Event Listener in testing?在测试中排除应用程序事件侦听器?
【发布时间】:2019-04-29 11:00:29
【问题描述】:

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

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

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

【问题讨论】:

  • 您使用的是什么类型的测试?
  • Junits,我在问题中添加了一个示例测试用例
  • 可以排除类还是方法?
  • 我要排除LoadCache()方法
  • 这里已经回答了这个问题 (stackoverflow.com/questions/46597149/…)

标签: spring-boot events caching junit


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2018-03-17
    • 2018-09-04
    • 2018-10-15
    • 1970-01-01
    • 1970-01-01
    • 2018-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多