Search code examples
javajunitacceptance-testing

Acceptance testing an incrementing value


I have a service which returns id of the created file, and afterwards it increments the id to identify the next file. For acceptance tests we have different project, therefore when I run the test it only passes if it is the first time this service is called. Is there any workaround I can use to overcome this issue?

@Test
public void createFileServiceTest(){
    int id = service.createFile("test.xml");

    assertEquals(0, id);
}

Solution

  • Your test does not match your specification/verbal explanation of the service. So you should not look for a workaround but cleanly redesign the test (or the service, or both).

    Redesigning the test, for instance

    @Test
    public void creatingAFileTwiceShouldYieldDifferentIDs(){
        int id1 = service.createFile("test.xml");
        int id2 = service.createFile("test.xml");
    
        assertThat(id1, not(equalTo(id2)));
    }
    
    @Test
    public void creatingFilesShouldYieldSuccessiveIDs(){
        int id1 = service.createFile("test1.xml");
        int id2 = service.createFile("test2.xml");
    
        assertThat(id1+1, is(equalTo(id2)));
    }
    

    Redesigning both, making the service more testable, for instance

    @Test
    public void resetServiceShouldResetGetMaxId(){
        service.reset();
        assertThat(service.getMaxId(), is(equalTo(0)));
    }
    
    @Test
    public void getMaxIdShouldYieldLatestId(){
        int id = service.createFile("test.xml");
        int newMaxId = service.getMaxId();
    
        assertThat(id, is(equalTo(newMaxId)));
    }
    
    @Test
    public void creatingFilesShouldYieldSuccessiveIDs(){
        int oldMaxId = service.getMaxId();
        int id = service.createFile("test.xml");
    
        assertThat(oldMaxId+1, is(equalTo(id)));
    }
    

    Of course, if you have concurrent access to the service, you should guarantee atomicity of your tests, or weaken your checks from (a+1==b) to (a<b).