Search code examples
javamockingjava-native-interfacejmockit

Mock a class have load native lib


I have a class with native method:

public class MyClass
{
    public static native boolean NativeMethod();
    static
    {
       System.loadLibrary("mynativelib");
    }
}

I am writing unit test for my project and some test case have call this native method. Currently I use jmockit to mock MyClass.

mynativelib is build to run on big endian machine, but those unit test is run on my linux PC which is little endian machine, so i got the fowllowing error when run those unit test:

wrong ELF class : ELFCLASS32 (Possible cause : endianness mismatch)

So my question is :

  • Is there a way to mock MyClass but not load mynativelib or can I mock only the native method, not mock the whole class?

Solution

  • You can mock the whole class while stubbing out the static initializer, by declaring a @Mocked(stubOutClassInitialization = true) MyClass mock field or parameter.

    This will only work, however, if the class has not been initialized during the test run, before it gets to the test with the @Mocked declaration.