0

My class has a method, that tries to perform some operations and return nano time after all operations are completed. When testing this method I get a problem, that test result is always different (because depends on current time).

How to test return value correctly? Is there way without PowerMock?

Example class:

class ExampleClass {
    public long performOperationsAndGetTimeNano(){
        //some operations...
        return Instant.now().getNano();
    }
    ...
}

Example test:

@ExtendWith(MockitoExtension.class)
class ExampleTest{
    private static final long EXPECTED_TIME = 555927900L;
    private ExampleClass subject;

    //init...

    @Test
    void performOperationAndGetTimeNano(){
        long actualTime = subject.performOperationAndGetTimeNano(); //always different result

        assertEquals(EXPECTED_TIME, actualTime); //always fails
    }
}

Thanks for your answers!

Roman
  • 181
  • 7
  • @Michael 1) Such solution makes me change the real implementation for the test. It's a bad practice 2) We reveal implementation details, if we provide such Supplier. I don't need to know, how does this method get completion time. Your solution also breaks my class incapsulation :( – Roman May 29 '22 at 13:45

1 Answers1

0

Question: How to test return value correctly? Fix: EXPECTED_TIME = EXPECTED_TIME + (CURTIME_IN_NANOSEC - EXPECTED_TIME), time digit till nano seconds(offset time till current nano second add to EXPECTED_TIME) ACTUAL_TIME = subject.performOperationAndGetTimeNano()--This gives time digit till nano seconds

private static final long EXPECTED_TIME = getExpectedLongTime();

long getExpectedLongTime(){} method in mocked java class and used in above class gives EXPECTED_TIME as above. Note in Mockito, Every input data is mocked by Mock java class which has sample Input Data.

B. Is there way without PowerMock? Fix: Yes there is, Simple JUnit like above. No need for mocked java class, we can write seperate method and use like above as in A.

Hope I Answered both your questions.