Search code examples
c++cmockingjava-native-interfacecunit

How to create a JNIEnv mock in C/C++


I am writing some JNI code in C that I wish to test using cunit. In order to call the JNI functions, I need to create a valid JNIEnv struct.

Does anyone know if there is a mocking framework for such a purpose, or who can give me some pointers on how to create a mock JNIEnv struct myself?


Solution

  • jni.h contains the complete structure for JNIEnv_, including the "jump table" JNINativeInterface_. You could create your own JNINativeInterface_ (pointing to mock implementations) and instantiate a JNIEnv_ from it.

    Edit in response to comments: (I didn't look at the other SO question you referenced)

    #include "jni.h"
    #include <iostream>
    
    jint JNICALL MockGetVersion(JNIEnv *)
    {
      return 23;
    }
    
    JNINativeInterface_ jnini = {
      0, 0, 0, 0, //4 reserved pointers
      MockGetVersion
    };
    
    // class Foo { public static native void bar(); }
    void Java_Foo_bar(JNIEnv* jni, jclass)
    {
      std::cout << jni->GetVersion() << std::endl;
    }
    
    int main()
    {
      JNIEnv_ myjni = {&jnini};
      Java_Foo_bar(&myjni, 0);
      return 0;
    }