Search code examples
javaunit-testingstatickotlinmockk

Mock static java methods using Mockk


We are currently working with java with kotlin project, slowly migrating the whole code to the latter.

Is it possible to mock static methods like Uri.parse() using Mockk?

How would the sample code look like?


Solution

  • After mockk 1.8.1:

    Mockk version 1.8.1 deprecated the solution below. After that version you should do:

    @Before
    fun mockAllUriInteractions() {
        mockkStatic(Uri::class)
        val uriMock = mockk<Uri>() 
        every { Uri.parse("test/path") } returns uriMock
    }
    

    mockkStatic will be cleared everytime it's called, so you don't need to unmock it before using it again.

    However, if that static namespace will be shared across tests it will share the mocked behavior. To avoid it, make sure to unmockkStatic after your suite is done.


    DEPRECATED:

    If you need that mocked behaviour to always be there, not only in a single test case, you can mock it using @Before and @After:

    @Before
    fun mockAllUriInteractions() {
        staticMockk<Uri>().mock()
        every { Uri.parse("http://test/path") } returns Uri("http", "test", "path")    //This line can also be in any @Test case
    }
    
    @After
    fun unmockAllUriInteractions() {
        staticMockk<Uri>().unmock()
    }
    

    This way, if you expect more pieces of your class to use the Uri class, you may mock it in a single place, instead of polluting your code with .use everywhere.