1

I'm working in a project which has some Java legacy code. One common pattern there is to create singletons using the "enum" approach:

enum MySingleton {
   INSTANCE;

   int answer;
   init {
     answer = 42;
   }

   int fun1() { return answer };

This INSTANCE object in reality has some complex dependencies which I cannot fulfill during unit tests. I thus would like to return a mocked MySingleton object whenever the caller uses MySingleton.INSTANCE. Is that possible?

2 Answers2

1

As per the official Mockk documentation, It can be done like below.

enum class Enumeration(val goodInt: Int) {
    CONSTANT(35),
    OTHER_CONSTANT(45);
}

mockkObject(Enumeration.CONSTANT)
every { Enumeration.CONSTANT.goodInt } returns 42
assertEquals(42, Enumeration.CONSTANT.goodInt)
Kanagalingam
  • 2,096
  • 5
  • 23
  • 40
0

you can mock enums using mockkObject(Enum)

Max Makeichik
  • 227
  • 4
  • 18