Chetan Joshi
Chetan Joshi

Reputation: 5711

How to mock static java method from kotlin , mockkStatic not working

I want to mock static method of java class from Kotlin test case.

I am using below code that does not work.

It always called actual method.

mockkStatic(Aes::class)
every { Aes.decrypt(PASSWORD, SECRET_KEY) } returns PASSWORD

Actual method in java class:

public static String decrypt(String text, String secretKey) {}

Upvotes: 2

Views: 2021

Answers (1)

Mariusz Brona
Mariusz Brona

Reputation: 1609

The good strategy for this is to use wrapper objects around static methods if there is no other way around (for example static method belongs to 3rd party library)

class AESWrapper {

    fun decrypt(String text, String secretKey) {
        return Aes.decrypt(text, secretKey)
    }

}

There are other solutions like PowerMock, but then you need to use PowerMockRunner as I remember which can limit you in the future

Upvotes: 3

Related Questions