Tests You Can Trust

Posted on

When working for Posten Bring thsi year, I did an internal presentation called "Tests You Can Trust". The presentation (online link) covers a wide range of strategies for building more trustworthy tests, including the use of Fakes and controlling time, with code examples (in a repo) for Java and Javascript.

The slides builds upon years of learnings, but I was especially influenced by published work by Anders Sveen and Asgaut Mjølne, which described their approach in a great talk on Javazone 2024 (in Norwegian), as well as in articles on the web, dealing with how they changed their approach from slow integration tests to consistently employing Fakes (not to be confused with stubs or mocks) to achieve fast tests that cover all their domain logic, while reserving integration tests for their integration layers.

Git for learning

In the presentation, I made use of Git as a pedagogical tool, using tags to show progress from a slow and error prone integration test based on real clock, randomness and sleeping threads, where I gradually improve it step-by-step to a state where it is fast and deterministic.

Step by step through the commits

In the Javascript code, I show how one can conceptually test animation code that is tightly bound to Javascript timers and the event loop, by utilising the fake-timers library from Sinon to drive the tests. This is a library I maintain and that is employed by Jest amongst others.

it("should move in chunks of 100 steps per frame", async () => {
    clock = fakeTimers.install();
    const player = new Player();

const movePromise = movePlayer(player, 300);

assert.equal(player.x, 0); await clock.tickAsync(3*16); assert.equal(player.x, 300);

return Promise.all([clock.runAllAsync(), movePromise]) });

Keywords: