使用JUnit進(jìn)行單元測試
作者:
網(wǎng)絡(luò)轉(zhuǎn)載 發(fā)布時間:
[ 2017/3/14 16:24:04 ] 推薦標(biāo)簽:
Junit 單元測試
異常測試
你可以測試代碼是否它拋出了想要得到的異常。expected 參數(shù)和 @Test 注釋一起使用,F(xiàn)在讓我們看看活動中的 @Test(expected)。
@Test(expected = NullPointerException.class)
public void testException() {
throw new NullPointerException();
}
所有測試代碼
代碼地址
package com.hollischuang.effective.unitest.service;
import org.junit.*;
/**
* @author Hollis 17/1/7.
*/
public class JUnitTest {
/**
* 只執(zhí)行一次,在整個類執(zhí)行之前執(zhí)行
*/
@BeforeClass
public static void beforeClass() {
System.out.println("in before class");
}
/**
* 只執(zhí)行一次,在整個類執(zhí)行之后執(zhí)行
*/
@AfterClass
public static void afterClass() {
System.out.println("in after class");
}
/**
* 每個測試方法被執(zhí)行前都被執(zhí)行一次
*/
@Before
public void before() {
System.out.println("in before");
}
/**
* 每個測試方法被執(zhí)行后都被執(zhí)行一次
*/
@After
public void after() {
System.out.println("in after");
}
// test case 1
@Test
public void testCase1() {
System.out.println("in test case 1");
}
// test case 2
@Test
public void testCase2() {
System.out.println("in test case 2");
}
/**
* 測試assertEquals
*/
@Test
public void testEquals() {
Assert.assertEquals(1 + 2, 3);
}
/**
* 測試assertTrue
*/
@Test
public void testTrue() {
Assert.assertTrue(1 + 2 == 3);
}
/**
* 測試assertFalse
*/
@Test
public void testFals() {
Assert.assertFalse(1 + 2 == 4);
}
/**
* 測試assertNotNull
*/
@Test
public void assertNotNull() {
Assert.assertNotNull("not null");
}
/**
* 測試assertNull
*/
@Test
public void assertNull() {
Assert.assertNull(null);
}
/**
* 測試fail和Ignore
*/
@Test
@Ignore
public void assertFail() {
Assert.fail();
}
/**
* 測試異常
*/
@Test(expected = NullPointerException.class)
public void testException() {
throw new NullPointerException();
}
/**
* 測試時間
*/
@Test(timeout = 1000)
public void testTimeoutSuccess() {
// do nothing
}
/**
* 測試時間
*/
@Test(timeout = 1000)
public void testTimeoutFailed() {
while (true) {
}
}
}
總結(jié)
本文主要介紹了JUnit的常見用法,后面會專門寫一篇文章介紹如何將JUnit和Spring集合到一起。