简体   繁体   中英

Parameterized JUnit Test

QUESTION: After putting my initialization into the actual @Parameters I no longer have a NullPointerException, is it possiuble that @Before isn't actually invoked before?! Is there a solution so I don't have to put it into my Paramters?

Solution:

@RunWith(value = Parameterized.class)
public class XQTest4Test {
    static XQueryTestHelper buildTest;
    static HeaderBodyPayloadTestcase[] arrayHdrInbPayTestcases;


    @Before
    public void initialize() throws Exception {
        buildTest = new XQueryTestHelper();
        buildTest.initialization();

        arrayHdrInbPayTestcases = buildTest.getHdrInbPayTestcases();
        System.out.println(arrayHdrInbPayTestcases[0].a);
    }

        @Parameter
        public HeaderBodyPayloadTestcase testcase;

        @Parameters(name = "{index}: pew")
        public static Iterable<? extends HeaderBodyPayloadTestcase> data() throws Exception {
            buildTest = new XQueryTestHelper();
            buildTest.initialization();

            arrayHdrInbPayTestcases = buildTest.getHdrInbPayTestcases();
            return Arrays.asList(arrayHdrInbPayTestcases);
        }




    @Test
    public void someTest() throws Exception{
    //  System.out.println(xq.toString());
        System.out.println(testcase.a);
        if(testcase.c.contains("HDR")){
            assertTrue(new XQueryTester(testcase.a,testcase.b).testHeader(testcase.c,testcase.d));
        }
        else if (testcase.c.contains("PAY")){
            assertTrue(new XQueryTester(testcase.a,testcase.b).testBody(testcase.c,testcase.d));

        }
        else {
            assertTrue(new XQueryTester(testcase.a,testcase.b).testInbound(testcase.c,testcase.d));
        }
    }

}

I think @Parameter annotation should help you. In this way you do not need a constructor with parameters.

@RunWith(Parameterized.class)
public class XQTest4Test {
    static XQueryTestHelper buildTest;
    static HeaderBodyPayloadTestcase[] arrayHdrInbPayTestcases;

    @Parameter
    public HeaderBodyPayloadTestcase testcase;

    @Parameters(name = "{index}: pew")
    public static Iterable<Object[]> data() {
        return Arrays.asList(new HeaderBodyPayloadTestcase[][]{arrayHdrInbPayTestcases});
    }

    // ...

}

And ensure that access modifier of field marked as @Parameter is public .

I would recommend you to do all the initialization in @Before or @BeforeClass methods. Depends on you logic.

This feature is well-documented on JUnit4 wiki

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM