使用Mockk模拟静态java方法

问题描述 投票:6回答:2

我们目前正在使用带有kotlin项目的java,慢慢地将整个代码迁移到后者。

是否可以使用Mockk模拟像Uri.parse()这样的静态方法?

示例代码如何?

java unit-testing static kotlin mockk
2个回答
7
投票

MockK允许模拟静态Java方法。它的主要目的是模拟Kotlin扩展函数,因此它没有PowerMock那么强大,但它仍然可以用于Java静态方法。

语法如下:

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") }  
}

更多细节在这里:http://mockk.io/#extension-functions


11
投票

除了oleksiyp答案:

在模拟1.8.1之后:

Mockk版本1.8.1弃用了以下解决方案。在那个版本之后你应该做:

@Before
fun mockAllUriInteractions() {
    mockkStatic(Uri::class)
    every { Uri.parse("http://test/path") } returns Uri("http", "test", "path")
}

qazxsw poi将在每次调用时被清除,因此您不再需要解锁它


弃用:

如果你需要那些模拟的行为总是在那里,不仅在一个测试用例中,你可以使用mockkStatic@Before来模拟它:

@After

这样,如果你希望你的类的更多部分使用Uri类,你可以在一个地方嘲笑它,而不是用@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() } 到处污染你的代码。

© www.soinside.com 2019 - 2024. All rights reserved.