0

At class level I have:

@ExtendWith(SpringExtension::class)
@AutoConfigureMockMvc
@SpringBootTest
@PrepareForTest(LocalDateTime::class)

My test method contains this:

@Test
fun `testMethod`() {
    PowerMockito.mockStatic(LocalDateTime::class.java)
    Mockito.`when`(LocalDateTime.now()).thenReturn(LocalDateTime.of(2018, 8, 22, 10, 0, 0, 0));
 }

My build.gradle.kts

testImplementation ( "org.mockito:mockito-core:3.5.9")
testImplementation("org.powermock:powermock-api-mockito2:2.0.7")
testImplementation("org.powermock:powermock-module-junit5:1.6.4")

The error:

org.mockito.exceptions.misusing.MissingMethodInvocationException: when() requires an argument which has to be 'a method call on a mock'. For example: when(mock.getArticles()).thenReturn(articles);

How to mock LocalDateTime.now() with Kotlin, Junit5, Spring Boot 2, Mockito, and PowerMock?

(I don't want to use LocalDateTime.now(clock) method)

Thomas Banderas
  • 1,681
  • 1
  • 21
  • 43
  • Does this answer your question? [How shoul I test logic that contains calls to aquire current date?](https://stackoverflow.com/questions/62259765/how-shoul-i-test-logic-that-contains-calls-to-aquire-current-date) – sidgate Sep 03 '20 at 15:58
  • I think, creating function with parameter "now" is a bad idea. Because you perhaps always expecting LocalDateTime.now(), so why to make param for it? If we could mock static methods via `PowerMock`, so why not to use it? – Thomas Banderas Sep 03 '20 at 16:03
  • 1
    using `LocalDateTime.now()` directly in the function body is code smell, and has *side effects*. Passing the dependency from outside makes it testable. You can name the method parameter whatever you want – sidgate Sep 03 '20 at 16:10
  • Ok, you're right. But the question comes down 'How to mock a static method' which does not work. – Thomas Banderas Sep 03 '20 at 16:18
  • check out `Mockito.mockStatic` on latest mockito version – sidgate Sep 03 '20 at 16:20
  • 1
    In general, no new software should require static calls. In this case, create a `Clock` interface and pass it as a parameter to the class (as Thomas mentioned above). In this way you can build your whole application using this class and have a number of test implementations (e.g. one that always return the same time, another where you can control how much time passes). – Augusto Sep 03 '20 at 22:47

0 Answers0