单元测试最佳实践要求使用控制反转,以确保单元测试彼此独立运行,即使它们依赖于单例实例(每个测试都有自己的“单例”)。
对于测试使用 JNI 来操作每个进程仅存在一次的 native 资源(例如终端)的库的建议是什么?
我不是在询问测试实际的 JNI 代码,而是在询问依赖于 native 代码作为副作用的 Java 代码。
请您参考如下方法:
和平常一样。
您创建您的测试代码(剪切)使用的库类的模拟,并验证您的剪切和该模拟之间的通信。
class JniUsageTest{
@Rule
public MockitoRule mockitoRule = MockitoJUnit.rule();
@Mock
private JniInterfaceClass jni;
@Test
public void testJniCommunication_SomethingToWrite_PassedToInterface(){
// arrange
doReturn("the Answer from JNI").when(jni).calledByCut(any(Object.class));
YorClassUnderTest cut = new YorClassUnderTest(jni);
// act
String resultContainingJniReturn = cut.doSomethingExpectedToWtiteToJni();
// assert
verify(jni,times(10)).calledByCut(any(Object.class));
assertThat(resultContainingJniReturn, containsString("the Answer from JNI"));
}
}