Junit单元测试学习笔记(一)
l 使用方法
下载junit
https://github.com/junit-team/junit/wiki/Download-and-Install
使用junit jar包
l 一个简单的test
1.创建类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | public class calc { /** * @param args */ public static int add( int first_num, int second_num) //add method { return first_num+second_num; } public static int minus( int first_num, int second_num) //minus method { return first_num-second_num; } public static int multiplication( int first_num, int second_num) //multiplication method { return first_num*second_num; } public static int division( int first_num, int second_num) { return first_num/second_num; // division will throw ArithmeticException when the second_num=0 } public static Boolean endless_loop() //endless loop { for (;;); //junit time out } } |
2.创建test case
TestCase类给我们提供了setUp方法和tearDown方法,setUp方法的内容在测试你编写的TestCase子类的每个testXxxx方法之前都会运行,而tearDown方法的内容在每个testXxxx方法结束以后都会执行。
我们创建setUp方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | import static org.junit.Assert.*; import org.junit.Before; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; public class calcTest { @Test public void testAdd() { assertEquals( 5 , calc.add( 2 , 3 )); } @Test public void testMunius() { assertEquals( 5 , calc.minus( 2 , 3 )); } @Ignore ( "testMultiplication() Not yet implemented" ) //ignore this case @Test public void testMultiplication() { assertEquals( 6 , calc.multiplication( 2 , 3 )); } @Test (expected=ArithmeticException. class ) // catch ArithmeticException exception public void testDivision () throws Exception { assertEquals(- 1 , calc.division( 2 , 0 )); } @Test (timeout = 10000 ) //defined time out =10 seconds public void testEndless_loop() { assertTrue( "true" ,calc.endless_loop()); // can’t return within 10 seconds } } |
3.结果
If add “@Ignore("testMultiplication() Not yet implemented") “
Then the test case will be ignored.
转载请注明出处:http://www.cnblogs.com/tobecrazy/

【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?