whoami

Lucas Jenß

cat /etc/motd

The Coding Journal ツ — Notes taken on an epic coding journey. Technical solutions, debugging notes, and practical guides from the trenches of software development.

Close-up of white dominoes with black dots standing on green felt surface, shallow depth of field, focused mood

ls -la ~/languages/

total 8
drwxr-xr-x
▶ PHP
▶ Ruby
▶ Scala
▶ C#
▶ JavaScript
▶ Objective-C
▶ Shell Scripting

ls -la ~/toolchain/

total 7
drwxr-xr-x
▶ Typo3
▶ Akka
▶ Capistrano
▶ Git
▶ MAMP
▶ Adobe Illustrator
▶ NSTrackingArea (Cocoa)

uname -a

platforms
drwxr-xr-x
▶ Mac OS X
▶ Unix

Mocking Android NDK native methods with Mockito

Mocking Android NDK native methods in unit tests with Mockito starts with a boundary that often causes confusion. A local JVM test executes your Java or Kotlin code, but it does not provide Android’s Bionic runtime or your compiled .so library. Calling the production native method can therefore fail with UnsatisfiedLinkError, an ABI mismatch, or the mockable Android SDK’s “Method not mocked” exception before the test reaches its assertion.

The dependable solution is to put a small Java or Kotlin interface in front of the JNI implementation and mock that interface. The production class loads the native library and implements the contract; application services depend on the contract. Mockito replaces only the boundary during a local test, while an instrumented test continues to exercise the C++ implementation.

Directly mocking a Java native declaration can be useful in some JVM configurations, but it does not intercept C++ functions, JNI callbacks, or code registered with RegisterNatives. Treating that technique as the whole strategy can create false confidence. A clear separation lets you control return values, verify calls, and reproduce errors without rebuilding native code for every Java test.

This matters for Australian development teams in Sydney, Melbourne, and Brisbane, where a shared CI server may run tests while the phone sits in another time zone. During an arvo build break, the practical question is usually whether business logic can be checked quickly, without turning a JNI fault into an afternoon of emulator setup. The local-first approach fits that workflow, while Google Play releases still need real-device coverage and correct GST-inclusive AUD pricing for Australian shoppers.

Why local unit tests need a native boundary

Android local unit tests execute on a desktop JVM, while NDK binaries are compiled for Android’s Bionic C library and device ABIs. The mockable android.jar supplied by the Android Gradle Plugin provides Java declarations, not a working native runtime. A direct call can therefore stop at UnsatisfiedLinkError, an incompatible .so error, or the SDK stub’s “Method not mocked” exception.

The practical choices differ in runtime, isolation, and native coverage:

Approach Test runtime What Mockito can control Native implementation
Mock a Java façade Local JVM The contract and its callers Not executed
Mock a Java native declaration Local JVM The intercepted Java call, where supported Not executed
Robolectric Local JVM with Android shadows Supported framework APIs Custom libraries still need a native runtime
Instrumented test Emulator or device App collaborators when needed Executed

A Java or Kotlin façade makes the boundary explicit. The interface owns the contract that application code needs; a separate implementation loads the library and exposes the native method. A local test mocks the interface, so no production implementation class is initialised and no .so file is needed.

Direct mocking of a Java native declaration is a narrower option. Mockito can replace the Java-level call for a mockable, non-final class in many JVM setups, but its static initialiser must not attempt to load an unavailable library. It still does not mock C++ symbols, intercept a JNI callback into C++, or alter a function registered with RegisterNatives. The boundary-first approach is consistent with the project notes on Aaron Orosen, where isolating the failing layer keeps fixes practical.

Build a mockable Java boundary

Start with the smallest contract that contains the JNI call. For example, a fingerprinting feature can expose bytes in and a digest out without leaking JNI pointer rules into the rest of the application:

public interface Fingerprint {
    String digest(byte[] payload);
}

public final class NdkFingerprint implements Fingerprint {
    static {
        System.loadLibrary("fingerprint");
    }

    @Override
    public native String digest(byte[] payload);
}

Production code receives Fingerprint through its constructor. The NdkFingerprint instance remains responsible for loading libfingerprint.so, while business logic never references that concrete class. A unit test can therefore create FingerprintService with a Mockito mock and exercise all the Java logic surrounding the native operation.

Keep the contract ordinary and avoid relying on advanced mock makers. Mockito 5 uses its inline mock maker by default, while older projects can add the inline artifact when final-type support is required. Neither setting supplies a native runtime. Also, unitTests.returnDefaultValues = true only changes stubs from the Android SDK jar; it does not load your library or turn an arbitrary JNI method into a working implementation.

Stub results and verify native calls

Mockito stubs the Java boundary before JNI converts Java objects into native handles. The values returned by the mock therefore describe the contract seen by the application, not the internals of the C++ function:

@Test
void returnsTheStubbedDigest() {
    Fingerprint fingerprint = mock(Fingerprint.class);
    byte[] payload = "native payload".getBytes(StandardCharsets.UTF_8);

    when(fingerprint.digest(any(byte[].class))).thenReturn("abc123");

    String result = new FingerprintService(fingerprint).summarize(payload);

    assertEquals("abc123", result);
    verify(fingerprint).digest(any(byte[].class));
}

Stubbing happens at the Java boundary, before JNI converts Java objects into native handles. Primitive methods default to zero or false and reference methods default to null, but explicit stubbing makes the expected contract clearer. For an error path, use thenThrow with the same exception type that the production adapter translates from a native status code; otherwise the test may describe behaviour the application never exposes.

Verification is equally useful. Use an ArgumentCaptor<byte[]> to inspect the exact payload, verifyNoMoreInteractions when a call should happen once, and InOrder when several native operations have a required sequence. Mockito cannot directly intercept C++ calling back into Java. Route such callbacks through a separate mockable collaborator if the Java side needs to control them.

Exercise the real JNI path

Local tests prove orchestration, not native correctness. Keep an Android instrumented test in src/androidTest that instantiates NdkFingerprint, invokes digest, and compares the result with a known vector. This catches missing libraries, wrong symbol names, malformed JNI signatures, and packaging errors that a JVM mock cannot reveal.

Run the instrumented suite on an emulator and on representative hardware. An x86_64 emulator exercises a different binary from an arm64 handset, and each ABI must match the .so packaged for that device. The journal’s guide to native Logcat logging is useful during this pass: add temporary markers around the JNI boundary, collect adb logcat output, and remove noisy logging before release.

On CI, keep local unit tests fast and broad, then schedule a smaller instrumented set for pull requests that touch native code. Preserve emulator logs and device test results as build artefacts so a failure after hours can be diagnosed without reproducing it on somebody’s laptop. For a release, include physical-device smoke tests because OEM builds can expose loader or filesystem differences.

Put the pattern into daily development

A practical routine is simple: every native capability gets a Java contract, a production adapter, and a Mockito-based unit test. Run the local suite on each commit, run instrumented coverage when the adapter, Gradle configuration, or native source changes, and avoid weakening assertions merely because a native result is inconvenient to calculate. The mock should model the application’s promised behaviour, including validation and error translation.

Treat the boundary as a security checkpoint as well. Values crossing from Java into native code still need range checks, size limits, and clear ownership rules; otherwise a lower-level defect becomes a crash or leak. The Coding Journal’s example of PHP traversal protection is a useful parallel because both cases show why input should be constrained before it reaches the component that can cause harm.

Start by creating the smallest Java interface around one troublesome JNI call, adding a deterministic Mockito test, and confirming that the local build no longer loads a .so. Keep one instrumented test for the real library, and require both suites to pass before the next Australian Google Play release. That keeps native debugging precise enough for an arvo-sized coffee break and gives Australian shoppers an Android build checked beyond the happy path.


cat ~/interests.json

KeyValue
editorTerminal-first workflow
osMac OS X / Unix
vcsGit, distributed version control
deployCapistrano, cron automation
graphicsSVG, Adobe Illustrator troubleshooting
networkingIP validation, SSH, VPN

git log --oneline --reverse

2013-10-30

Solving SVG import issues in Adobe Illustrator CS6 and CC

When importing an SVG into Illustrator, the operation fails with an unknown error [CANT]. A workaround for this Adobe-side bug.

2013

Solving NDK build issues on OS X

Troubleshooting native development kit compilation problems on Mac OS X.

2013

Programmatically adding PHP generated TypoScript to the backend configuration

Integrating dynamically generated TypoScript into Typo3 backend setups using PHP.

2013

ArgumentError: Could not parse PKey: no start line

Debugging an SSH key parsing error encountered during deployment.

2011-08-04

Validating IP-Addresses in PHP

Using PHP filter functions with flags like FILTER_FLAG_IPV4 and FILTER_FLAG_IPV6, and understanding how filter_var handles reserved IP addresses.

2011-07-09

Cocoa: Using NSTrackingArea

A short tutorial on using Cocoa's NSTrackingArea to capture mouseEntered and mouseExited events.


cat ~/contact.txt

github: github.com/x3ro
stackoverflow: x3ro
coderwall: coderwall.com/x3ro
twitter: @x3rames