简体   繁体   中英

Mocking methods that call JNI with Mockk

I am trying to add unit tests to an existing Android app that has some JNI libraries (only for ARM). I am using Mockk and Junit4 , and I have the following:

This static class is mine, and it calls the initialize method of the external SDK (which I was given, I don't have access to their code).

internal class DeviceSDK {
    companion object {
        internal fun initialize() {
            val success = ExternalSDK.getInstance().init() // it fails here 2
            return success
        }
    }
}

The init method calls loadLibrary for some native libraries.

In my test class, I have the following:

class MyDeviceTest {
    private val sdkInstance = mockk<ExternalSDK>()
   
    @Before
    fun setUp() {
        mockkStatic(ExternalSDK::class) {
            every { ExternalSDK.getInstance() } returns sdkInstance
        }

        every { sdkInstance.init() } returns true

        mockkStatic(DeviceSDK::class) {
            every { DeviceSDK.initialize() } just runs // it fails here 1
        }
    }

    ...
}

This fails where I have put the it fails here 1 comment, because it calls the line where I put the it fails here 2 comment, and that tries to load the libraries, giving me an UnsatisfiedLinkError .

But I really don't get why, since in first place I'm mocking the method DeviceSDK.initialize() so it should not run. But if it ran, anyway I'm mocking the ExternalSDK init method, so that shouldn't run as well.

Is there anything that I'm not getting right? Thank you.

Finally, the problem was because companion objects in Kotlin are not actually static classes even though they accomplish the same thing. So you have to change mockkStatic for mockkObject and then it will not call the SDK.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM