JUnit单元测试--IntelliJ IDEA
單元測試的基本使用
一、環境配置
? ? ?使用idea IDE 進行單元測試,首先需要安裝JUnit 插件。
? ? ? ? ? 1.安裝JUnit插件步驟
? ? ? ? ? ? ? File-->settings-->Plguins-->Browse repositories-->輸入JUnit-->選擇JUnit Generator V2.0安裝。
? ? ? ? ? 2.使用JUnit插件
? ? ? ? ? ? ?在需要進行單元測試的類中,使用快捷鍵alt+insert,選擇JUnit test,選擇JUnit4。
二、單元測試
代碼Demo:
@Testpublic void testAdd() {assertEquals(2, new UserDao().add(1, 1));}1>注意事項:
1、測試方法上面必須使用@Test注解進行修飾。
2、測試方法必須使用public void 進行修飾,不能帶有任何參數。
3、新建一個源代碼目錄用來存放測試代碼。
4、測試類的包應該與被測試類的包保持一致。
5、測試單元中的每一個方法必須獨立測試,每個測試方法之間不能有依賴。
6、測試類使用Test做為類名的后綴(非必要)。
7、測試方法使用test作為方法名的前綴(非必要)。
2>錯誤解析:
1、Failure 一般是單元測試使用的斷言方法判斷失敗引起,說明預期結果和程序運行結果不一致。
2、error 是有代碼異常引起的,他產生于測試代碼本身中的Bug。
3、測試用例是不是用來證明你是對的,而是用來證明你沒有錯。
3>測試流程:
代碼Demo:
@BeforeClasspublic static void setUpBeforeClass() throws Exception {}@AfterClasspublic static void setUpAfterClass() throws Exception {}@Beforepublic void before() throws Exception {}@Afterpublic void after() throws Exception {}1、@BeforeClass所修飾的方法在所有方法加載前執行,而且他是靜態的在類加載后就會執行該方法,
?在內存中只有一份實例,適合用來加載配置文件。
2、@AfterClass所修飾的方法在所有方法執行完畢之后執行,通常用來進行資源清理,例如關閉數據庫連接。
3、@Before和@After在每個測試方法執行前都會執行一次。
4>常用注解
1、@Test(excepted=XX.class) 在運行時忽略某個異常。
2、@Test(timeout=毫秒) 允許程序運行的時間。
3、@Ignore 所修飾的方法被測試器忽略。
4、RunWith 可以修改測試運行器 org.junit.runner.Runner
5>測試套件
? 測試套件是組織測試類一起運行的測試類。具體如下:
代碼Demo:
@RunWith(Suite.class) @Suite.SuiteClasses({UserTest1,UserTest2,UserTest3}) public class SuiteTest{}注意事項:
1、作為測試套件的入口類,類中不能包含任何方法。
2、更改測試運行器Suite.class。
3、將需要運行的測試類放入Suite.SuiteClasses({})的數組中。
6>參數化設置
需要測試的僅僅是測試數據,代碼結構是不變的,只需要更改測試數據。
代碼Demo:
@RunWith(Parameterized.class) public class parameterTest {int expected = 0;int input1 = 0;int input2 = 0;@Parameterspublic static Collection<Object[]> t() {return Arrays.asList(new Object[][]{{3,1,2},{5,2,3}});}public parameterTest(int expected,int input1,int input2) {this.expected = expected;this.input1 = input1;this.input2 = input2;}@Testpublic void testAdd() {assertEquals(expected, UserDao.add(input1,input2));}}具體步驟:
1、更改默認的測試運行器為@RunWith(Parameterized.class)。
2、聲明變量來存放預期值和測試值。
3、聲明一個返回值為Collection的公共靜態方法,并用@Parameters修飾。
4、為測試類聲明一個帶有參數的公共構造函數,并在其中為他聲明變量賦值。
以上為基于IntelliJ IDEA 進行的單元測試。
?
轉載鏈接:http://www.cnblogs.com/huaxingtianxia/p/5563111.html
轉載于:https://www.cnblogs.com/luohengstudy/p/7681835.html
總結
以上是生活随笔為你收集整理的JUnit单元测试--IntelliJ IDEA的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux使用freetds 连接连远程
- 下一篇: 网络对抗技术 实验报告 三