Hacker News new | ask | show | jobs
by throwaway_fjmr 1783 days ago
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.
1 comments

> 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 :)