使用Mockk模拟静态Java方法 [英] Mock static java methods using Mockk
问题描述
我们目前正在使用带有kotlin项目的Java,将整个代码缓慢地迁移到后者.
We are currently working with java with kotlin project, slowly migrating the whole code to the latter.
是否可以使用Mockk模拟诸如Uri.parse()
的静态方法?
Is it possible to mock static methods like Uri.parse()
using Mockk?
示例代码看起来如何?
推荐答案
除了oleksiyp答案:
In addition to oleksiyp answer:
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
会在每次调用时清除,因此您不再需要取消模拟操作
mockkStatic
will be cleared everytime it's called, so you don't need to unmock it anymore
已弃用:
如果您需要始终保持模拟行为,不仅在单个测试用例中,还可以使用@Before
和@After
对其进行模拟:
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()
}
这样,如果您希望类的更多部分使用Uri类,则可以在一个地方进行模拟,而不用在任何地方都使用.use
污染代码.
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.
这篇关于使用Mockk模拟静态Java方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!