Подтвердить что ты не робот

Ошибка Java JUnit с параметрами

Я создаю приложение Java на основе JRE 6. Я использую JUnit 4 для создания параметризованных тестов. Я получаю эту ошибку:

The annotation @Parameterized.Parameters must define the attribute value

в строке, содержащей аннотацию:

@Parameterized.Parameters

Ниже приведен код, который, как мне кажется, имеет отношение к этой проблеме:

import static org.junit.Assert.assertEquals;

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

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import calc.CalculatorException;
import calc.ScientificCalculator;

@RunWith(Parameterized.class)
public class ScientificCalculatorTest extends BasicCalculatorTest{

    /** Provides an interface to the scientific features of the calculator under test */
    private ScientificCalculator sciCalc;
    private double a, b;


    @Before
    @Override
    public void setUp() throws Exception {
        sciCalc = new ScientificCalculator();
        //Make sure that the basic functionality of the extended calculator
        //hasn't been broken.
        theCalc = sciCalc;
    }

    /**
     * Constructor. Is executed on each test and sets the test values to each pair in the data sets.
     * @param nr1 the first number in the tested pair.
     * @param nr2 the second number in the tested pair.
     */
    public ScientificCalculatorTest(double nr1, double nr2){
        a = nr1;
        b = nr2;
    }


    @Parameterized.Parameters
    public static Collection<Object[]> testGenerator() {
        return Arrays.asList(new Object[][] {
                //General integer values | -/+ combinations
                {  -100,  -100},
                {  -100,   100},
                {   100,  -100},
                {   100,   100}
        });
    }

Мне удалось найти несколько связанных вопросов, таких как . К сожалению, в моей ситуации они не помогают.

Что я пробовал и не работал:

  • удаление "extends BasicCalculatorTest" из объявления класса

  • добавление тестовых функций, которые используют аннотацию @Test

  • импорт org.junit.runners.Parameterized и использование @Parameters вместо @Parameterized.Parameters

Мне нужно упомянуть, что я использовал очень похожую реализацию (в первую очередь аннотации и testGenerator()) в другом проекте без каких-либо проблем. Реализация следует за учебниками, доступными в Интернете, например this, this и this.

Приветствуется всякая помощь в решении этой ошибки.

4b9b3361

Ответ 1

попробуйте следующее:

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

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
public class So15213068 {
    public static class BaseTestCase {
        @Test public void test() {
            System.out.println("base class test");
        }
    }
    @RunWith(Parameterized.class) public static class TestCase extends BaseTestCase {
        public TestCase(Double nr1,Double nr2) {
            //super(nr1,nr2);
            this.nr1=nr1;
            this.nr2=nr2;
        }
        @Test public void test2() {
            System.out.println("subclass test "+nr1+" "+nr2);
        }
        @Parameters public static Collection<Object[]> testGenerator() {
            return Arrays.asList(new Object[][]{{-100.,-100.},{-100.,100.},{100.,-100.},{100.,100.}});
        }
        double nr1,nr2;
    }
}

выход:

subclass test -100.0 -100.0
base class test
subclass test -100.0 100.0
base class test
subclass test 100.0 -100.0
base class test
subclass test 100.0 100.0
base class test

Ответ 2

Это должно быть потому, что вы расширяете BaseTestCase. Я скопировал ваш код, не переходя из базового класса, тесты прошли правильно.

Попробуйте вызвать super.setUp() в настройках

например.

@Before
@Override
public void setUp() throws Exception {
    super.setUp();
    sciCalc = new ScientificCalculator();
    //Make sure that the basic functionality of the extended calculator
    //hasn't been broken.
    theCalc = sciCalc;
}

Ответ 3

Вы пропустите ниже импорт, я думаю.

import org.junit.runners.Parameterized.Parameters;