Search code examples
androidc++android-ndkgoogletest

Compiling Google Test cases on Android NDK?


I am trying to compile a simple unit test for Android NDK code using the Google Test framework. My code follows the README nearly verbatim:

Application.mk

APP_STL :=  gnustl_shared

Android.mk

# Build module
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := jniLib
LOCAL_SRC_FILES := jniLib.cpp
include $(BUILD_SHARED_LIBRARY)

# Build unit tests
include $(CLEAR_VARS)
LOCAL_MODULE := jniLib_unittest
LOCAL_SRC_FILES := jniLib_unittest.cpp
LOCAL_SHARED_LIBRARIES := jniLib
LOCAL_STATIC_LIBRARIES := googletest_main
include $(BUILD_EXECUTABLE)
$(call import-module,third_party/googletest)

jniLib.cpp

jint Java_test_nativetest_MainActivity_add(JNIEnv* env, jobject jThis, jint x, jint y) {
    return x + y;
}

jniLib.h

#pragma once
#include <jni.h>
extern "C" {
    jint Java_test_nativetest_MainActivity_add(JNIEnv* env, jobject jThis, jint x, jint y);
}

jniLib_unittest.cpp

#include <gtest/gtest.h>
Test(AddTest, FivePlusFive) {
    EXPECT_EQ(10, add(5, 5));
}

When I try to build with ndk-build, I get the following compilation error:

jni/jniLib_unittest.cpp:10:9: error: expected constructor, destructor, or type
conversion before '(' token make.exe: 
*** [obj/local/armeabi/objs/jniLib_unittest/jniLib_unittest.o] Error 1

What am I doing wrong?


Solution

  • My code had a number of errors, but the primary issue is that the test declaration is case sensitive: it is TEST, not Test. My corrected code is as follows:

    Application.mk

    # Set APP_PLATFORM >= 16 to fix: http://stackoverflow.com/q/24818902
    APP_PLATFORM = android-18
    APP_STL :=  gnustl_shared
    

    jniLib.cpp

    #include "jniLib.h"
    jint Java_test_nativetest_MainActivity_add(JNIEnv* env, jobject jThis, jint x, jint y) {
        return doAdd(x, y);
    }
    
    int doAdd(int x, int y) {
        return x + y;
    }
    

    jniLib.h

    #pragma once
    #include <jni.h>
    extern "C" {
        jint Java_test_nativetest_MainActivity_add(JNIEnv* env, jobject jThis, jint x, jint y);
    }
    
    int doAdd(int x, int y);
    

    jniLib_unittest.cpp

    #include <gtest/gtest.h>
        /**
        * Unit test the function 'add', not the JNI call
        * 'Java_test_nativetest_MainActivity_add' 
        */
    TEST(AddTest, FivePlusFive) {
        EXPECT_EQ(10, add(5, 5));
    }
    
    int main(int argc, char** argv) {
        testing::InitGoogleTest(&argc, argv);
        return RUN_ALL_TESTS();
    }