Class EurekaTestHelpers


  • public class EurekaTestHelpers
    extends Object
    • Constructor Detail

      • EurekaTestHelpers

        public EurekaTestHelpers()
    • Method Detail

      • resetStatsMonitor

        public static void resetStatsMonitor()
        Resets the static ScheduledExecutorService that lives inside Eureka's StatsMonitor class, and which causes problems during tests when we may need to start and stop Eureka multiple times. By "reset" we mean that the ScheduledExecutorService which has been shut down is replaced (via reflection which makes the protected field accessible and removes its final modifier) with a new instance that (obviously) has not been shut down. Yes, THIS IS A TOTAL HACK!!!!!!! Also, we are pretty sure this will NOT work in Java 17 and beyond, and we don't currently have a solution. Please read on for more details, if you dare.

        The StatsMonitor class contains a protected static final ScheduledExecutorService that is initialized once in a static initialization block. This executor is started when Eureka starts and is shut down when Eureka is shut down.

        Specifically, the executor is scheduled in the constructor of StatsMonitor. In the Eureka lifecycle, this actually occurs when an instance of the StatsTimer (a subclass of StatsMonitor) is constructed.

        The executor shutdown occurs in the static ServoControl.shutdown() method which is called in turn by DefaultEurekaServerContext.shutdown() during the Eureka shut down process. Because of this design using a static field shared by multiple instances, there is no way to "reset" that executor to a new one on each test, so we have to do this reflection hack to reset it.

        Why don't we use Mockito's mockStatic or PowerMock's mockStatic to mock the method in ServoControl which calls shutdown() on the executor? Because...

        • Mockito's mockStatic does not support doNothing() which is needed because the method is void.
        • PowerMock doesn't support Junit 5 without "tricking" the runner to fall back to Junit 4 which is yuck!