Search code examples
integration-testingcode-organization

How can I break up a long, multi-step integration test?


I have a really long integration test that simulates a sequential process involving many different interactions with a couple of Java servlets. The servlets' behavior depends on the values of the parameters being posted in the request, so I wanted to test every permutation to make sure my servlets are behaving as expected.

Currently, my integration test is in one long function called "testServletFunctionality()" that goes something like this:

//Configure a mock request
//Post request to servlet X
//Check database for expected changes
//Re-configure mock request
//Re-post request to servlet X
//Check database for expected changes
//Re-configure mock request
//Post request to servlet Y
//Check database for expected changes
...

and each configure/post/check step has about 20 lines of code, so the function is very long.

What is the proper way to break up or organize a long, sequential, repetitive integration tests like this?


Solution

  • The main problem with integration tests (IT) is usually that the setup is very expensive. Tests usually should not depend on each other and the order in which they are executed but for ITs, test #2 will always fail if you don't run test #1 (login).

    Sad.

    The solution is to treat these tests like production code: Split long methods into several smaller ones, build helper objects that perform certain operations, so you can do this in your test:

    @Test
    public void someComplexText() throws Exception {
        new LoginHelper().loginAsAdmin();
        ....
    }
    

    or move this code into a base test class:

    @Test
    public void someComplexText() throws Exception {
        loginHelper().loginAsAdmin();
        ....
    }