Migrate unit-test to RegisterNatives.

This commit is contained in:
Dan Albert
2025-09-18 15:47:32 -07:00
committed by Dan Albert
parent 032d6b90f0
commit 63739c1903
3 changed files with 30 additions and 36 deletions

View File

@@ -47,6 +47,7 @@ android {
}
dependencies {
implementation project(":base")
implementation libs.appcompat
implementation libs.material
implementation libs.androidx.constraintlayout

View File

@@ -8,49 +8,25 @@ project("unittest")
include(AppLibrary)
find_package(base REQUIRED CONFIG)
find_package(googletest REQUIRED CONFIG)
find_package(junit-gtest REQUIRED CONFIG)
add_app_library(adder OBJECT adder.cpp)
# Creates and names a library, sets it as either STATIC
# or SHARED, and provides the relative paths to its source code.
# You can define multiple libraries, and CMake builds them for you.
# Gradle automatically packages shared libraries with your APK.
add_app_library( # Sets the name of the library.
add_app_library(
unittest
# Sets the library as a shared library.
SHARED
# Provides a relative path to your source file(s).
$<TARGET_OBJECTS:adder>
native-lib.cpp)
# Searches for a specified prebuilt library and stores the path as a
# variable. Because CMake includes system libraries in the search path by
# default, you only need to specify the name of the public NDK library
# you want to add. CMake verifies that the library exists before
# completing its build.
find_library( # Sets the name of the path variable.
log-lib
# Specifies the name of the NDK library that
# you want CMake to locate.
log)
# Specifies libraries CMake should link to your target library. You
# can link multiple libraries, such as libraries you define in this
# build script, prebuilt third-party libraries, or system libraries.
native-lib.cpp
)
target_link_libraries( # Specifies the target library.
unittest
# Links the target library to the log library
# included in the NDK.
${log-lib})
PRIVATE
base::base
log
)
add_app_library(app_tests SHARED adder_test.cpp)
target_link_libraries(app_tests

View File

@@ -1,8 +1,25 @@
#include <base/macros.h>
#include <jni.h>
#include "adder.h"
extern "C" JNIEXPORT jint JNICALL
Java_com_example_unittest_MainActivity_add(JNIEnv*, jobject, jint a, jint b) {
return add((int)a, (int)b);
}
jint Add(JNIEnv*, jobject, jint a, jint b) { return add((int)a, (int)b); }
extern "C" JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* _Nonnull vm,
void* _Nullable) {
JNIEnv* env;
if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK) {
return JNI_ERR;
}
jclass c = env->FindClass("com/example/unittest/MainActivity");
if (c == nullptr) return JNI_ERR;
static const JNINativeMethod methods[] = {
{"add", "(II)I", reinterpret_cast<void*>(Add)},
};
int rc = env->RegisterNatives(c, methods, arraysize(methods));
if (rc != JNI_OK) return rc;
return JNI_VERSION_1_6;
}