Home > Back-end >  Skip a parameter in MockK unit test, Kotlin
Skip a parameter in MockK unit test, Kotlin

Time:03-31

I use MockK library for unit testing.

Tested method contains strings that don't have meaning for a result. I want to check other variables, but have to define a behaviour of strings because they are used in tested methods.

For instance,

every {
    resources.getQuantityString(R.plurals.age, 10, 10)
} returns "10 years"
every {
    resources.getString(
        R.string.surname,
        "surname"
    )
} returns "surname"

How can I omit parameters in these methods? So that I could pass any integer instead of 10, any string instead of "surname"? In this case a result of resources.getString won't have matter. I don't want to calculate a value of each parameter for a test. Just mock a behaviour.

CodePudding user response:

You can use answers instead of returns and have a plethora of options to return something depending on the input, e.g.

every {
    resources.getQuantityString(any(), any(), any())
} answers { "${arg<Int>(1)} years" }

every {
    resources.getString(any(), any())
} answers { secondArg() }

Check out this table for the different parameters you can use in an answer.

  • Related