Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock Locale using Mockk

Tags:

android

mockk

I'm trying to use Mockk to mock the call to Locale.getDefault(), however I can't seem to get it working. Has anyone successfully used Mockk to mock the Locale?

My very simple test class

@Test
fun testName() {
    val defaultLocale = mockk<Locale>()

    mockkStatic(Locale::class)

    every { Locale.getDefault() } returns defaultLocale
}

The error I get

*** java.lang.instrument ASSERTION FAILED ***: "!errorOutstanding" with message transform method call failed at JPLISAgent.c line: 844
like image 598
Joao Sousa Avatar asked Aug 16 '19 08:08

Joao Sousa


1 Answers

There's no need to mock Locale as it is part of the Java framework and will run in a Unit Test without issue.

package java.util.Locale.java

If you are testing various locales you can set the desired locale before each test runs by calling Locale#setDefault with either one of the predefined country constants in the Locale class or enter the language and country code strings into the constructor:

setDefault(Locale.US) 
setDefault(Locale.GERMANY)
setDefault(Locale.FRANCE)

// with a language code
val locale = Locale("en-US")

// with a language and country code
val locale = Locale("en", "US") 

Locale.setDefault(locale)

Important

You should reset the locale after each test class has finished to ensure the locale is in an expected state for the next tests that are about to be run. This can be maintained by storing the locale the class enters with and reverting to it after all the tests have run, with the @BeforeClass and @AfterClass JUnit method annotations that run once before the classes tests run and once after all tests have run.

private lateinit var storedLocale: Locale

@BeforeClass
fun beforeClass() {
    storedLocale = Locale.getDefault()
}

..
// various tests that manipulate the default locale
..

@AfterClass
fun afterClass() {
     Locale.setDefault(storedLocale)
}
like image 71
JakeB Avatar answered Nov 15 '22 04:11

JakeB