如何使用groovy在eclipse中使用JUnit?

时间:2012-08-07 10:14:16

标签: java groovy junit

我是JUnit的新手,关注this tutorial但需要对我的测试用例提出一些建议和理解

我在一个文件夹中有一些xmls(每个3MB-6MB),对于每个xml,我需要测试一些标签是否包含某些值,有时将该值与特定结果匹配。

那么对于每个测试,如何在循环内执行所有@Test函数?我是否需要在循环内调用@Test函数(因为它们被自动调用)?

请帮助我在这个背景下进行JUnit。感谢

Junit testcase

public class SystemsCheck {

    def fileList

    @Before
    public void setUp() throws Exception {

        def dir = new File("E:\\temp\\junit\\fast")
        fileList = []

        def newFile=""
        dir.eachFileRecurse (FileType.FILES) { file ->
            fileList << file
          }

        fileList.each {
            //how should i test all @Test with it.text
            println it.text
          }     
    }

    @Test 
    void testOsname(){
        NixSystems ns=new NixSystems()
        /*checking if tag is not empty*/
        //assertEquals("Result","",ns.verifyOsname())
    }

    @Test
    public void testMultiply(){
        NixSystems ns=new NixSystems()
        assertEquals("Result", 50, ns.multiply(10, 5))
    }

}

class NixSystems {

    public def verifyOsname(xml){
        return processXml( xml, '//client/system/osname' )
    }

    public def multiply(int x, int y) {
        return x * y;
    }


    def processXml( String xml, String xpathQuery ) {
        def xpath = XPathFactory.newInstance().newXPath()
        def builder     = DocumentBuilderFactory.newInstance().newDocumentBuilder()
        def inputStream = new ByteArrayInputStream( xml.bytes )
        def records     = builder.parse(inputStream).documentElement
        xpath.evaluate( xpathQuery, records )
      }
}

1 个答案:

答案 0 :(得分:2)

JUnit为此类测试提供了专用功能 - Parameterized JUnit Tests。 这基本上是你已经完成的,但是要简洁,标准化。

以下是Java的代码 - 可以轻松转换为Groovy

@RunWith(Parameterized.class)
public class TestCase {
    private Type placeholder1;
    private Type placeholder2;
    ...
    public TestCase(Param1 placeholder1, Param2 placeholder2, ...) {
        this.placeholder1 = placeholder1;
    }

    @Parameters
    public static Collection<Object[][]> data() {
        //prepare data
        //each row is one test, each object in row is placeholder1/2... for this test case 
    }

    @Test
    public void yourTest() {...}
}

org.junit.runners.Parameterized的JavaDocs中,你可以找到Fibonnaci数字测试的例子。