6

I have a code that looks somehow like this:

MyObject getMyObject() {
    Instant now = Instant.now();
    return myService.doSomething(now);
}

I know that PowerMock is not supported in JUnit 5, but I am wondering maybe there is a solution at least for standard API like dates.

Right now I am mocking the Instant instance with Mockito.any() which is incorrect as my test won't fail if I pass a wrong Instant.

Sasha Shpota
  • 9,436
  • 14
  • 75
  • 148

1 Answers1

4

You can move the creation of current Instant to a package level method:

MyObject getMyObject() {
    Instant now = getCurrentInstance();
    return myService.doSomething(now);
}

Instant getCurrentInstant(){
  Instant.now();
}

Then in your test you can spy on the SUT and mock the getCurrentInstant method:

Sut sut = spy(new Sut());
doReturn(testInstance).when(sut).getCurrentInstant();

sut.getMyObject();

Here is an article I wrote on Mockito Spying if you need a further read.

Maciej Kowalski
  • 25,605
  • 12
  • 54
  • 63
  • I am not quite sure how it solves my problem. If I extract the `Instant.now()` to a new method I solve the problem with the original method. But now I have to test `getCurrentInstant()` method and I run into the same problem. – Sasha Shpota May 31 '19 at 07:42
  • Why you need to test something which does not have logic and is not a public method? – Maciej Kowalski May 31 '19 at 07:45
  • It does have a logic, why do you think that returning current date is not a logic? One can easily break the method and no tests will fail. – Sasha Shpota May 31 '19 at 07:48
  • 1
    you should not use when.then on spies.. as you invoke real method in the process – Maciej Kowalski May 31 '19 at 08:17
  • Logic to me is a conditional statement, loop, change of object state, exception being thrown.. but what we extracted here is literally a sort of getter. Besides you cannot test reliably a current date retrieval. You have to rely on it working and having it wrapped with a meaninngful name. Another thing why would want to test that java native method works? – Maciej Kowalski May 31 '19 at 08:22