5

I am facing problem in figuring this out.

I am using caching in my application and loading it on application startup using 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.
}

This works all fine when I am running the application. The problem however occurs when I run the test cases, the LoadCache() is being called when the setup is being run. I don't want this to run while the tests are being executed.

This is a sample test case

@RunWith(SpringRunner.class)
@SpringBootTest(classes = GameServiceApplication.class)
public class GameEngineTest {
    @Test
    public void testSomeMethod() {
        // some logic
    }
}
Akshaya Kumar T
  • 134
  • 2
  • 13

1 Answers1

2

If you can move your EventListener in a separate class and make it as Bean, then you can use mockBean in your tests to mock a real implementation.

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

or you can use profiles to run this listener only in production mode.