存在 JNI API 调用时的 JUnit 测试覆盖率

JUnit Test coverage when there exists a JNI API call

我正在编写 JUnit 测试用例。我有一个 class 包含 APIs 调用 JNI APIs.

public class Test {

    public native int getId_native();

    public void doSomething() {
        // do init
        int id = getId_native();
        // Get name by Id
    }

}

我正在为 doSomething() API 编写单元测试。我面临的问题是,一旦 JNI API(getId_native()) 被调用,UnsatisfiedLinkError 就会被抛出并在我的 JUnit 测试中被捕获,然后测试结束。控制不会进一步测试本机函数之后的代码行。这减少了项目中所有类似方法的代码覆盖率。

由于本地方法在同一个 class 中声明,我也无法模拟 class。

谁能帮我解决这个问题?

谢谢。

您需要在测试期间加载本机库。您可以通过多种方式加载 dll。例如:

System.load("path to your dll with native method");

如果原始库不适合测试,则构建具有单元测试所需功能的模拟本机 dll。