Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Skip a parameter in MockK unit test, Kotlin

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,

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading