Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I am assuming this is easier in Ruby because you can monkey patch classes?

Mockito in Java has a nifty way of doing this with Mockito.mockStatic:

  @Test
  public void mockTime() throws InterruptedException {
    LocalDateTime fake = LocalDateTime.of(2021, 7, 2, 19, 0, 0);

    try (MockedStatic<LocalDateTime> call = Mockito.mockStatic(LocalDateTime.class)) {
      call.when(LocalDateTime::now).thenReturn(fake);

      assertThat(LocalDateTime.now()).isEqualTo(fake);
      Thread.sleep(2_000);
      assertThat(LocalDateTime.now()).isEqualTo(fake);
    }

    LocalDateTime now = LocalDateTime.now();
    assertThat(now).isAfter(fake);
    assertThat(now).isNotEqualTo(fake);
  }
Or you can pass a Clock instance and use .now(clock). That Clock then can be either a system clock or a fixed value.



> I am assuming this is easier in Ruby because you can monkey patch classes?

Yes, that was my point. I see it's possible in Java though, hurts my eyes a bit but possible :)




Consider applying for YC's Fall 2025 batch! Applications are open till Aug 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: