Mock static java methods using Mockk

主宰稳场 提交于 2019-12-05 14:54:23

问题


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?


回答1:


MockK allows mocking static Java methods. The main purpose for it is mocking of Kotlin extension functions, so it is not as powerful as PowerMock, but still does it's job even for Java static methods.

The syntax would be following:

staticMockk<Uri>().use {
    every { Uri.parse("http://test/path") } returns Uri("http", "test", "path")

    assertEquals(Uri("http", "test", "path"), Uri.parse("http://test/path"))

    verify { Uri.parse("http://test/path") }  
}

More details here: http://mockk.io/#extension-functions




回答2:


In addition to oleksiyp answer:

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)
    every { Uri.parse("http://test/path") } returns Uri("http", "test", "path")
}

mockkStatic will be cleared everytime it's called, so you don't need to unmock it anymore


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.



来源:https://stackoverflow.com/questions/49762409/mock-static-java-methods-using-mockk

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!