使用 Mockk 模拟静态 java 方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/49762409/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Mock static java methods using Mockk
提问by Andrzej Sawoniewicz
We are currently working with java with kotlin project, slowly migrating the whole code to the latter.
我们目前正在用java with kotlin 项目,慢慢将整个代码迁移到后者。
Is it possible to mock static methods like Uri.parse()
using Mockk?
是否可以像Uri.parse()
使用 Mockk一样模拟静态方法?
How would the sample code look like?
示例代码会是什么样子?
回答by Kerooker
In addition to oleksiyp answer:
除了 oleksiyp 答案:
After mockk 1.8.1:
在模拟 1.8.1 之后:
Mockk version 1.8.1 deprecated the solution below. After that version you should do:
Mockk 1.8.1 版弃用了以下解决方案。在该版本之后,您应该执行以下操作:
@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
mockkStatic
每次调用时都会被清除,因此您不再需要取消模拟
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
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.
这样,如果您希望更多的类使用 Uri 类,您可以在一个地方模拟它,而不是.use
到处污染您的代码。
回答by oleksiyp
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.
MockK 允许模拟静态 Java 方法。它的主要目的是模拟 Kotlin 扩展函数,因此它不如 PowerMock 强大,但即使对于 Java 静态方法也能完成它的工作。
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
更多细节在这里:http: //mockk.io/#extension-functions