How to mock Java static block

114 views Asked by At

I have a following Java class in a 3rd party library:

public final class SomeFactory {
  public static native someMethod1()
  public static native someMethod2()

  private SomeFactory() {
  }

  static {
    System.loadLibrary("some_lib");
  }
}

And this crashes my tests, because loading that some_lib fails.

java.lang.UnsatisfiedLinkError: no some_lib in java.library.path: /usr/java/packages/lib:/usr/lib/x86_64-linux-gnu/jni:/lib/x86_64-linux-gnu:/usr/lib/x86_64-linux-gnu:/usr/lib/jni:/lib:/usr/lib

So how can I mock this class? I'm suing MockK and Kotest.

I've tried different combinations of just mockk(), mockkStatic(), mockkConstructor() and others, but nothing works. I've even tried mockkStatic(System::class), but it seems like it broke the JVM completely.

1

There are 1 answers

0
Pitel On BEST ANSWER

What I did was create a new object, that wraps the original one:

object SomeWrapper {
  fun someMethod1() = SomeFactory.someMethod1()
}

and then in MockK, just mock the object:

mockkObject(SomeWrapper)
every { SomeWrapper.method1() } returns mockk()