Question

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?

Was it helpful?

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;
}

OTHER TIPS

Mocking JNI sounds like a world of pain to me. I think you are likely to be better off mocking the calls implemented in Java, and using Junit to test the functionality on the java side

Quote: "jnimock is implemented on top of gmock. It provides two C++ classes 'JNIEnvMock' and 'JavaVMMock' to separately mock 'JNIEnv' and 'JavaVM'."

https://github.com/ifokthenok/jnimock

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top