天天看点

【随记】一次测试多个JUnit单元测试类(方法)

如何使用junit做单元测试?

答案很简单:搭好环境写好测试类,运行就可以了!但如果我有很多个测试类(方法),如何做到一次运行多个测试类呢?

首先创建个待测试的bean

package test;
public class testClass {
    public static String sayHello(){
        return "Hello";
    }
           

然后创建junit测试类,如下:

注意必须继承TestCase类

package test;

import junit.framework.TestCase;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class testClassTest extends TestCase{

    private testClass test;



    @After
    public void s2(){
        System.out.println("over");
    }


    @Before
    public void setUp() throws Exception {
        test = new testClass();
        System.out.println("start");
    }

    @Test
    public void testSayHello() throws Exception{
        assertEquals("Hello", testClass.sayHello());
    }

    @Test
    public void testSayHello2() throws Exception{
        assertEquals("Hello", "Hello");
    }
}
           

到目前为止,测试类已经创建完成,如果运行测试类的话,就可以对相应方法进行测试,一下要讲的就是如何对多个测试类进行测试。

创建TestRunning类

package test;

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;

public class TestRunning extends TestCase {
    public static void main(String[] args) {
        junit.textui.TestRunner.run(suite());
    }

    public static Test suite() {
        TestSuite suite = new TestSuite();
        suite.addTestSuite(testClassTest.class);
//在此添加测试类即可
        //suite.addTestSuite(TestStudent.class);
        return suite;
    }
}
           

当运行时,控制台会告诉你运行的结果,如果有不符合断言的情况,控制台会输出详细信息。

这样,可以对局部或者全部的测试类进行测试,而不需要对手动运行每个测试类。

当然了,junit还可以通过另外一种方式对某个测试类的某个方法进行测试,如下代码所示:

package test;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
public class TestRunning extends TestCase {

 public static void main(String[] args) {
  junit.textui.TestRunner.run(suite());
 }
 public static Test suite(){
  TestSuite suite = new TestSuite();
  suite.addTest(new TestStudent("testGet"));
  suite.addTest(new TestStudent("testSet"));
  return suite;

 }
}
           

以上suite()中对TestStudent的testGet和testSet方法进行了测试。

不过这也是手动在添加代码吧?如果有开发出注解的方法,应该会更好。

继续阅读