Video in progress

Strong Middle 🧪 Testing

The test below always passes on a local machine but fails now and then on CI. What could be the cause?

class TagServiceTest {
    static final TagService service = new TagService(); // static Map cache inside

    @Test
    void teglarni_qaytaradi() {
        service.add("java");
        service.add("spring");
        assertEquals("[java, spring]", service.all().toString()); // all() returns a HashSet
    }

    @Test
    void bosh_boshlanadi() {
        assertTrue(service.all().isEmpty());
    }
}

The tests share a static cache, and the result depends on the order they run in. On top of that, HashSet iteration order isn't guaranteed, so comparing with toString() is wrong. You need to clean the state in every test and compare without regard to order.

📖 Answer

There are two independent problems here.

The first is shared state. service is static, and the cache inside it is static too. If teglarni_qaytaradi runs first, bosh_boshlanadi sees a filled cache and fails. Locally the IDE runs the methods in one order, but on CI there may be a different fork, parallel execution, or a random order. JUnit 5's default order is deterministic but not "obvious": it depends on a hash of the method names.

The second is HashSet order. Right now it prints [java, spring], but if the elements added, the JDK version or the hash collisions change, it could print [spring, java]. Comparing with a string ties you to an implementation detail.

The fix:

class TagServiceTest {
    TagService service;

    @BeforeEach
    void setUp() { service = new TagService(); }   // the cache should be an instance field

    @Test
    void teglarni_qaytaradi() {
        service.add("java");
        service.add("spring");
        assertThat(service.all()).containsExactlyInAnyOrder("java", "spring");
    }
}

The static cache inside TagService should change too: it's not only a test problem, and in prod it can also leak data between tenants or requests. A test is often the first to expose design mistakes like this.