JUnit - Параметризованный тест

JUnit - параметризованный тест

В JUnit вы можете передать параметры в метод модульного тестирования с помощью следующих методов:

  1. Конструктор

  2. Внедрение полей через@Parameter

P.S Tested with JUnit 4.12

1. MatchUtils - Тест с несколькими параметрами

Простая операция добавления.

MathUtils.java

package com.example.examples;

public class MathUtils {

    public static int add(int a, int b) {
        return a + b;
    }

}

1.2 MatchUtils – Parameterized via Constructor

Параметры передаются в метод тестирования через конструктор.

ParameterizedTest.java

package com.example;

import com.example.examples.MathUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

import java.util.Arrays;
import java.util.Collection;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

@RunWith(value = Parameterized.class)
public class ParameterizedTest {

    private int numberA;
    private int numberB;
    private int expected;

    // Inject via constructor
    // for {8, 2, 10}, numberA = 8, numberB = 2, expected = 10
    public ParameterizedTest(int numberA, int numberB, int expected) {
        this.numberA = numberA;
        this.numberB = numberB;
        this.expected = expected;
    }

    // name attribute is optional, provide an unique name for test
    // multiple parameters, uses Collection
    @Parameters(name = "{index}: testAdd({0}+{1}) = {2}")
    public static Collection data() {
        return Arrays.asList(new Object[][]{
                {1, 1, 2},
                {2, 2, 4},
                {8, 2, 10},
                {4, 5, 9},
                {5, 5, 10}
        });
    }

    @Test
    public void test_addTwoNumbes() {
        assertThat(MathUtils.add(numberA, numberB), is(expected));
    }

}

1.3 MatchUtils – Parameterized via Field Injection

Параметры передаются в метод тестирования через внедрение поля.

ParameterizedTest.java

package com.example;

import com.example.examples.MathUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import org.junit.runners.Parameterized.Parameter;

import java.util.Arrays;
import java.util.Collection;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

@RunWith(value = Parameterized.class)
public class ParameterizedTest {

    //default value = 0
    @Parameter(value = 0)
    public int numberA;

    @Parameter(value = 1)
    public int numberB;

    @Parameter(value = 2)
    public int expected;

    @Parameters(name = "{index}: testAdd({0}+{1}) = {2}")
    public static Collection data() {
        return Arrays.asList(new Object[][]{
                {1, 1, 2},
                {2, 2, 4},
                {8, 2, 10},
                {4, 5, 9},
                {5, 5, 10}
        });
    }

    @Test
    public void test_addTwoNumbes() {
        assertThat(MathUtils.add(numberA, numberB), is(expected));
    }

}

Note
Для@Parameters атрибут «имя» является необязательным, он помогает идентифицировать отдельные тестовые случаи, предоставляя уникальное имя.

What is {0}, {1} and {2}?
Если параметр равен «\ {3, 4, 7}», то {0} = 3, {1} = 4, {2} = 7.

Выход

junit-parameterized-1

2. DomainUtils - тест с одним параметром

Другой простой класс, проверка доменного имени.

DomainUtils.java

package com.example.examples;

import java.util.regex.Pattern;

public class DomainUtils {

    private static final String DOMAIN_NAME_PATTERN = "^((?!-)[A-Za-z0-9-]{1,63}(?

2.1 DomainUtils Parameterized Test

Параметры передаются в метод тестирования через внедрение поля.

ParameterizedTest.java

package com.example;

import com.example.examples.DomainUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

@RunWith(value = Parameterized.class)
public class Parameterized2Test {

    //default value = 0
    @Parameter
    public String domainName;

    //Single parameter, use Object[]
    @Parameters(name = "{index}: testDomain - {0}")
    public static Object[] data() {
        return new Object[]{
                "google.com",
                "example.com",
                "twitter.com"
        };
    }

    @Test
    public void test_valid_domain() {
        assertThat(DomainUtils.isValid(domainName), is(true));
    }

}

Выход

junit-parameterized-2

Note
TestNG более гибок в плане передачи параметров в модульные тесты, прочтите этотTestNG parameter test.