2

我在我的 Junit 测试用例中使用 ErrorCollector,目的是打印出错误而不是停在错误的位置。我通过使用不带参数的方法成功地尝试了 ErrorCollector。但是为了减少代码重复(我在没有参数的情况下编写了 6 次相同的方法;因为我使用 6 个文件进行比较,如我的代码中所示),我希望有一个通用方法可以用来实现相同的目的打印出错误并继续检查。当我尝试使用带有参数的方法时,我得到了异常“方法应该没有参数”..

以下是我的代码。

            import org.gdal172.ogr.ogr;
            import org.hamcrest.CoreMatchers;
            import org.junit.Rule;
            import org.junit.Test;
            import org.junit.rules.ErrorCollector;
            import org.junit.runner.JUnitCore;
            import org.junit.runner.Result;
            import org.junit.runner.notification.Failure;

            public class DGNTester {
                private ReadDGN readDgn = new ReadDGN();
                private LinkedHashMap<String, Integer> layerMapCountForCompare = new LinkedHashMap<String, Integer>();
                @Rule
                public  ErrorCollector collector = new ErrorCollector();

                private File output = null;
                static {
                    // perform OGR format registration once
                    if (ogr.GetDriverCount() == 0)
                        ogr.RegisterAll();
                }

                /**
                 * @param args
                 */
                public static void main(String[] args) {

                    DGNTester dTest = new DGNTester();

                    String dgnFileName_43k10 = "input\\43k10.dgn";
                    String dgnFileName_43k11 = "input\\43k11.dgn";
                    String dgnFileName_43k12 = "input\\43k12.dgn";

                    //The six files iam using as input.

                    dTest.test(dgnFileName_43k10, "dvd");
                    dTest.test(dgnFileName_43k10, "all");
                    dTest.test(dgnFileName_43k11, "dvd");
                    dTest.test(dgnFileName_43k11, "all");
                    dTest.test(dgnFileName_43k12, "dvd");
                    dTest.test(dgnFileName_43k12, "all");

                }

                @Test
                public void test(String fileName, String inputType) {
                    System.out.println("FOR FILE -->" + fileName);
                    System.out
                            .println("---------------------------------------------------------------------------------------------------");
                    String fileIdentifier = fileName.substring(6, 11);
                    String dstFilePath = null;
                    String outputName = null;
                    if (layerMapCountForCompare != null)
                        layerMapCountForCompare.clear();

                    if (inputType.equals("dvd")) {
                        dstFilePath = "F:\\eclipse_helios_3.6.1_64_bit_with_jre_and_add-ons\\eclipse\\Resources\\DST\\dvd.dst";
                        outputName = "output\\outputfile_" + fileIdentifier
                                + "_dvd.dst.txt";
                    }
                    if (inputType.equals("all")) {
                        dstFilePath = "F:\\eclipse_helios_3.6.1_64_bit_with_jre_and_add-ons\\eclipse\\Resources\\DST\\AllLayers.dst";
                        outputName = "output\\outputfile_" + fileIdentifier + ".txt";
                    }
                    layerMapCountForCompare = readDgn.getLayerFeatureCount(fileName,
                            dstFilePath);

                    // Read the text output file and Compare with the map. These are the six out put files against each input file

                    output = new File(outputName);

                    if (output.exists()) {
                        try {
                            Set keys = layerMapCountForCompare.keySet();
                            Iterator itr = keys.iterator();
                            String key = "";
                            Integer val;

                            String line;
                            BufferedReader br = new BufferedReader(new FileReader(output));
                            while ((line = br.readLine()) != null && itr.hasNext()) {
                                key = (String) itr.next();
                                val = layerMapCountForCompare.get(key);
                                String compare = key + "=" + val;
                                compare.trim();
                                line.trim();
                                //When i print this out in a positive scenario; i am able to see the values of 'compare' and 'line' as same
                                /*System.out.println("COMPARE >>> " + compare
                                        + " --------------- AND --------- Line " + line);*/

                                assertEquals("Comparing input and output", line, compare);
                            }
                            br.close();

                        } catch (FileNotFoundException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    } else {
                        System.out.println("Output file does not exist");
                    }

                }

                public void assertEquals(String msg, Object expected, Object actual) {

                    collector.checkThat(actual, CoreMatchers.equalTo(expected));

                }

            }

在我之前的例子中;我没有使用参数的地方;

    Result result = JUnitCore.runClasses(DGNTester.class);

    for (Failure failure : result.getFailures()) {
                System.out.println(failure.toString());
            }
            if (result.wasSuccessful()) {
                System.out.println("Tests finished successfully...");
            }

此代码有助于触发测试方法并打印适当的方法。
您能否指导我如何使用我的通用方法,它需要两个参数来利用 ErrorCollector。

如何将错误收集器用于带参数的 junit 测试方法

4

1 回答 1

0

@Test注解不支持在签名中带有参数的测试方法。

例子:

尝试运行该方法brokenTest将引发异常。JUnit 中正确的测试方法应如下所示correctTest

/** This method uses parameters in the signature. It will not work! */
@Test
public void brokenTest(String fileName) {...}

/** This correct test method has no parameters in its signature. */
@Test
public void correctTest() {...}

使用 JUnit 进行参数化测试

要支持参数化测试,您可以使用@RunWith(Parameterized.class)注释(类级别)。

测试类需要一个返回参数的静态方法Iterable(如List对象)。用 注释此方法@Parameters

此外,每个使用的参数都需要一个public(!) 成员变量,每个参数都用 ,@Parameter(0)等注释@Parameter(1)

因此,JUnit 将为使用该方法testWithParameters()生成的每个测试用例运行。createParameters()它会自动将正确的参数分配给@Parameter(N) 字段(firstParameter/secondParameter)。

您可以根据需要生成任意数量的参数。

通过引用它们的字段名称,根据需要在测试方法中使用这些参数。

您提供的课程摘录的示例:

@RunWith(Parameterized.class)
public class DGNTester {
    @Rule
    public  ErrorCollector collector = new ErrorCollector();

    /**
     * Method that generates the parameters.
     * Each testValues.add(...) line produces a new test case.
     *
     * @return Array with test values.
     */
    @Parameters
    public static Iterable<Object[]> createParameters() {
        List<Object[]> testValues = new ArrayList<>();

        try {
            testValues.add(new Object[]{"pre-Case1-Value1", "Case1-Value2"});
            testValues.add(new Object[]{"Case2-Param1", "Case2-Value2"});
            testValues.add(new Object[]{"pre-Case3-Value1", "Case3-Value2"});
        }

        return testValues;
    }

    /** The first parameter. */
    @Parameter(0)
    public String firstParameter;

    /** The second parameter. */
    @Parameter(1)
    public String secondParameter;

    /** Test using the parameters generated by createParameters(). 
      * In this example we check, if the first parameter is equal to the
      * concatenation of the String "pre-" and the second parameter */
    @Test
    public void testWithParameters() {
        assertThat("Wrong parameter values", firstParameter, 
            is("pre-" + secondParameter));
    }

    ...
}
于 2015-04-21T13:04:01.667 回答