天天看點

【随記】一次測試多個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方法進行了測試。

不過這也是手動在添加代碼吧?如果有開發出注解的方法,應該會更好。

繼續閱讀