Hacker News new | ask | show | jobs
by lkitching 1783 days ago
If you want to use DI, in java 8 you could inject a java.time.Clock instance in the constructor and provide a fixed instance at the required time in your test e.g.

    Instant testNow = ...
    User u = new User(Clock.fixed(testNow, ZoneOffset.UTC));
    u.sayCurrentTime();
although it would be better design to have sayCurrentTime take a date parameter instead of depending on an external dependency.
1 comments

Yes that was my point. You don't need DI or to structure your code any differently in Ruby/JS/Python. You just mock a method.
In my experience the need to mock out individual methods like this is an indication that the code is badly structured in the first place. The time source is effectively a global variable so in this example you'd want to pass the time as a parameter to `sayCurrentTime` and avoid the need to mock anything in the first place. A lot of C#/java codebases do seem to make excessive use of mocks and DI in this way though.