1. 程式人生 > >java-junit單元測試工具

java-junit單元測試工具

java-junit單元測試工具

Junit下載地址:http://pan.baidu.com/s/1eQfQQw6

優點:

    1.不用寫把方法寫main函式裡面進行測試。

    2.不用進行人工對比。

操作:

1.匯入junit測試單元的jar包

 

2.在方法上面新增 @Test就可以了

 

3.選中方法→右擊→Run AS→JUnit Test

 

4.測試結果:綠條測試通過,紅條測試失敗。

junit要注意的細節:

1. 如果使用junit測試一個方法的時候,在junit視窗上顯示綠條那麼代表測試正確,

如果是出現了紅條,則代表該方法測試出現了異常不通過。

2. 如果點選方法名、 類名、包名、 工程名執行junit分別測試的是對應的方法,類、 包中 的所有類的test方法,工程中的所有test方法。

3.  @Test測試的方法不能是static修飾與不能帶有形參。

4. 如果測試一個方法的時候需要準備測試的環境或者是清理測試的環境,那麼可以@Before、 @After 、@BeforeClass、              @AfterClass這四個註解。

@Before、 @After 是在每個測試方法測試的時候都會呼叫一次, @BeforeClass、 @AfterClass是在所有的測試方法測試之前與測試之後呼叫一次而已。

 

斷言(Assert)使用:

 

         Assert.assertSame(new String("asdf"), "asdf");//使用==比較結果為true

        Assert.assertNotSame(new String("a"), "a");//使用==比較結果為false

        Assert.assertNull("asdf");//應是null

        Assert.assertNotNull(null);//應是非null

        Assert.assertTrue(true);//應是true

        Assert.assertFalse(false);//應是false

        Assert.assertEquals(new String("asdf"), "asdf");//使用equals()比較結果為true