How to Execute Something Multiple Times in Java


When writing unit / integration tests, you often want to execute something multiple times, with different configurations / parameters / arguments every time. For instance, if you want to pass a “limit” or “timeout” or any other argument value of 1, 10, and 100, you could do this:

@Test
public void test() {
    runCode(1);
    runCode(10);
    runCode(100);
}

private void runCode(int argument) {

    // Run the actual test
    assertNotNull(new MyObject(argument).execute());
}

Exracting methods is the most obvious approach, but it can quickly get nasty, as these extracted methods are hardly re-usable outside of that single test-case and thus don’t really deserve being put in their own methods. Instead, just use this little trick:

@Test
public void test() {

    // Repeat the contents 3 times, for values 1, 10, 100
    for (int argument : new int[] { 1, 10, 100 }) {

        // Run the actual test
        assertNotNull(new MyObject(argument).execute());
    }

    // Alternatively, use Arrays.asList(), which has a similar effect:
    for (Integer argument : Arrays.asList(1, 10, 100)) {

        // Run the actual test
        assertNotNull(new MyObject(argument).execute());
    }
}

Tags: , , , , , ,

6 responses to “How to Execute Something Multiple Times in Java”

  1. agentgt says :

    You can also look at jUnit’s @Parameterized which I have used often: http://junit.sourceforge.net/javadoc/org/junit/runners/Parameterized.html

  2. ftr says :

    I dislike this approach because your test fails if the test n test fails. You do not get an overview of all test cases, you don’t know if the test n+1 fails or works correctly.

    Parameterized tests are the way to go here as mentionend by agentgt

    • lukaseder says :

      Add “n” or “n+1″ to the assertion message, and you’ll know… Of course, this can be used outside of writing tests. Tests are just one example

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 2,190 other followers

%d bloggers like this: