Idea配置JUnit4單元測試入門
阿新 • • 發佈:2019-01-07
pom.xml檔案配置
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>RELEASE</version>
<scope>test</scope>
</dependency>
然後建立一個和src同級別的資料夾叫test(邏輯程式碼放src裡,測試程式碼放test裡是個好習慣)。
接著在IntelliJ IDEA裡還要把這個test資料夾要設定成測試檔案的根目錄,右鍵選中 Mark Directory As -> Test Sources Root
然後建立測試類(包名一致,類名在要測試的類名後加上Test也是個好習慣)。
public class IndexBuilderTest {
@Test
public void testStart() throws Exception {
System.out.println("---testStrat()----");
IndexBuilder indexBuilder=new IndexBuilder();
indexBuilder.start();
// assertEquals(true,false);
}
}
然後選中MathTest類ctrl + shift + F10執行一下。
JUnit4利用JDK5的新特性Annotation,使用註解來定義測試規則。
這裡講一下以下幾個常用的註解:
@Test:把一個方法標記為測試方法
@Before:每一個測試方法執行前自動呼叫一次
@After:每一個測試方法執行完自動呼叫一次
@BeforeClass:所有測試方法執行前執行一次,在測試類還沒有例項化就已經被載入,所以用static修飾
@AfterClass:所有測試方法執行完執行一次,在測試類還沒有例項化就已經被載入,所以用static修飾
@Ignore:暫不執行該測試方法