It depends on your class and what you want to do:
If you want to mock all properties of a class, and the class is not final, then use a mocking framework like Mockito.
MyClass mocked = Mockito.mock(MyClass.class);
Mockito.when(mocked.getTimestamp()).thenReturn(**/ your value **/ )
If your class is final, you want to only mock this single property or then property is final:
You can create a static factory, that provides you with Instant
and then in your test replace the factory.
class TimeFactory {
private static Supplier<Instant> INSTANT_SUPPLIER = Instant::now;
public static Instant getInstant(){ return INSTANT_SUPPLIER.get(); }
public static void setInstantSupplier(Supplier<Instant> new){ INSTANT_SUPPLIER= supplier; }
}
And in your constructor:
this.timestamp = null == timestamp ? TimeFactory.getInstant().toEpochMilli() : timestamp;
Now in your test, you can us the setter method:
TimeFactory.setInstantSupplier(()-> /*Your value*/ )
// create your object
Just remember to return to default supplier after the test:
TimeFactory.setInstantSupplier(Instant::now);
If your property is not final, then add a package setter, that can be used in your test.
Next solution (not recommended though) is to use reflection. But this is not mocking, this is using force to set a private (event final) properties.
There is also a way to overwrite the clock for tests