/java/

JUnit Parameterized test

2013-07-18 00:08:47

Maven:


<dependency>
<groupid>junit</groupid>
<artifactid>junit</artifactid>
<version>4.6</version>
</dependency>

Test:

import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import static org.junit.Assert.assertEquals;

@RunWith(Parameterized.class)
public class PostServiceTest {

    private List

<string> parameter;

    public PostServiceTest(List<string> testParameter) {
        this.parameter = testParameter;
    }

    @Parameters
    public static Collection<object[]> data() {
        List<string> params1 = Arrays.asList(new String[] {"lorem", "ipsum"});
        List<string> params2 = Arrays.asList(new String[] {"michal", "szalek"});
        List<string> params3 = Arrays.asList(new String[] {"pl", "btbw"});

        return Arrays.asList(new Object[][] {{ params1 },{ params2 }, {params3}});
    }

    @Test
    public void connectString() {
        PostService postService = new PostService();
        String connect = postService.connectString(parameter.get(0), parameter.get(1));

        assertEquals(connect, parameter.get(0)+"_"+parameter.get(1));
    }
}

public class PostService {
    public String connectString(String first, String second){
        return first+"_"+second;
    }
}

No important note: Annotations @Test @Test(expected = Exception.class) @Test(timeout=100) @Before @After @BeforeClass @AfterClass @Ignore

Assert statements fail(String) assertTrue([message], boolean condition) assertsEquals([String message], expected, actual) assertsEquals([String message], expected, actual, tolerance) assertNull([message], object) assertNotNull([message], object) assertSame([String], expected, actual) assertNotSame([String], expected, actual)

Combine test class into a test suite.