Feature: mocking native methods alike System.currentTimeMillis()
See original GitHub issueI wanted to mock System.currentTimeMillis(), but it results in a Stackoverflow error.
@Test
fun `System`(){
mockkStatic(System::class)
every { System.currentTimeMillis() } returns 1L
assertEquals(System.currentTimeMillis(), 1L)
}
00:18:57.851 [main] DEBUG io.mockk.proxy.jvm.StaticProxyMaker - Transforming class java.lang.System for static method interception
Exception in thread "main" java.lang.StackOverflowError
at java.lang.Class.getDeclaredMethod(Class.java:2127)
at java.lang.System.getSecurityManager(System.java:334)
at java.lang.Class.checkMemberAccess(Class.java:2337)
at java.lang.Class.getDeclaredMethod(Class.java:2127)
Issue Analytics
- State:
- Created 5 years ago
- Reactions:13
- Comments:10 (1 by maintainers)
Top Results From Across the Web
mocking native methods alike System.currentTimeMillis()
Feature : mocking native methods alike System.currentTimeMillis()
Read more >JMockit mocking System.currentTimeMillis() - Stack Overflow
My final solution is to create a MockUp for System, that only mocks the method currentTimeMillis(): private static class SystemMock extends ...
Read more >Overriding System Time for Testing in Java - Baeldung
In this quick tutorial, we'll focus on different ways to override the system time for testing. Sometimes there's a logic around the current ......
Read more >How do you mock this? - Google Groups
Is this a feature you want from Mockito? ... You want this feature to mock System. ... I've never had to mock static...
Read more >System currentTimeMillis junit
Java mock Date ... You could do this by using PowerMock, which augments Mockito to be able to mock static methods. You could...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Closed stale thread - I know - but it still comes up in search results. I have a workaround that is not clearly expressed elsewhere:
You can’t mockkstatic
Systembut you can mockkstaticCalendar. So in your production code use:instead of:
then in your tests you can do something like:
It beats the hell out of messing around with DI.
In case you don’t want to create a new calendar instance everytime (by calling
Calendar.getInstance().timeInMillis) here is another workaround:in production replace System call with the helper
in test: