Hazelcast instances and caches stay alive after running unit test

67 Views Asked by At

So I did not mock HazelcastInstance because my code needs the data from the cache in order to test their functionality. If I mock HazelcastInstance, I will not be able to mock getMap() method which returns the cached data. In case I do mock it, I cannot make it return a dummy object because IMap<> cannot be initialized as far I know. So this is not possible in kotlin code

myDummyMap : IMap<Object, Object> = (instance of IMap) when(instance.getmap).thenReturn(myDummyMap)

Now the problem is that after unit test, instances of hazel persist and not only that but join the main application cluster

2

There are 2 best solutions below

0
Orçun Çolak On

You can easily mock the IMap instead of mocking an HZ instance. This is much easier than starting an HZ instance for unit testing.

@Test
void testMockIMap() {
  IMap<String, Integer> mockMap = Mockito.mock(IMap.class);
  Mockito.when(mockMap.get("key1")).thenReturn(1);
  Integer result = mockMap.get("key1");
  Assertions.assertEquals(1, result);
}
0
Stephen C On

Now the problem is that after unit test, instances of hazel persist and not only that but join the main application cluster.

You should create a test cluster and run your tests against that cluster rather than the main (production) cluster. My understanding is that it is just a matter of supplying a different configuration ...

There are a number of ways to run code after all JUnit tests have completed; see Run code in junit 5 after all tests in all test classes terminated.

There is even a section of the Hazelcast documentation that talks about JUnit testing a Hazelcast application ... including a recipe for shutting down the cluster when the tests have completed; see https://docs.hazelcast.com/hazelcast/5.3/test/testing.