1、junit 使用教程几乎所有程序员都听说过Junit的大名,但不知真正懂得运用它的人有多少,我便是其中的一个小白。知道Junit是用来测试的,但却把“宝刀”当成了“菜刀”用。为了从此不再菜鸟,特此总结整理了下Junit的知识点。1. 建立Junit测试类1. 右击test测试包,选择New-Oher.2. 在窗口中找到Junit,选择Junit Test Case3. 输入名称(Name),命名规则一般建议采用:类名+Test。Browse.选择要测试的类,这里是StudentService。4. 勾选要测试的方法5. 生成后,效果如下:这里import static是引入Assert类中静态
2、属性或静态方法的写法。原来要Assert.fail(),现在只需直接fial()即可,即省略了Assert。其实不通过Junit新建向导来建立也可以,随便建立一个新类后,只需在方法上加入Test注解即可。2. 核心断言断言是编写测试用例的核心实现方式,即期望值是多少,测试的结果是多少,以此来判断测试是否通过。1. 断言核心方法assertArrayEquals(expecteds, actuals)查看两个数组是否相等。assertEquals(expected, actual)查看两个对象是否相等。类似于字符串比较使用的equals()方法assertNotEquals(first, sec
3、ond)查看两个对象是否不相等。assertNull(object)查看对象是否为空。assertNotNull(object)查看对象是否不为空。assertSame(expected, actual)查看两个对象的引用是否相等。类似于使用“=”比较两个对象assertNotSame(unexpected, actual)查看两个对象的引用是否不相等。类似于使用“!=”比较两个对象assertTrue(condition)查看运行结果是否为true。assertFalse(condition)查看运行结果是否为false。assertThat(actual, matcher)查看实际值是否满
4、足指定的条件fail()让测试失败2. 示例java view plain copy print?packagetest;importstaticorg.hamcrest.CoreMatchers.*;importstaticorg.junit.Assert.*;importjava.util.Arrays;importorg.hamcrest.core.CombinableMatcher;importorg.junit.Test;publicclassAssertTestsTestpublicvoidtestAssertArrayEquals()byteexpected=trial.getB
5、ytes();byteactual=trial.getBytes();org.junit.Assert.assertArrayEquals(failure-bytearraysnotsame,expected,actual);TestpublicvoidtestAssertEquals()org.junit.Assert.assertEquals(failure-stringsnotsame,5l,5l);TestpublicvoidtestAssertFalse()org.junit.Assert.assertFalse(failure-shouldbefalse,false);Testpu
6、blicvoidtestAssertNotNull()org.junit.Assert.assertNotNull(shouldnotbenull,newObject();TestpublicvoidtestAssertNotSame()org.junit.Assert.assertNotSame(shouldnotbesameObject,newObject(),newObject();TestpublicvoidtestAssertNull()org.junit.Assert.assertNull(shouldbenull,null);TestpublicvoidtestAssertSam
7、e()IntegeraNumber=Integer.valueOf(768);org.junit.Assert.assertSame(shouldbesame,aNumber,aNumber);/JUnitMatchersassertThatTestpublicvoidtestAssertThatBothContainsString()org.junit.Assert.assertThat(albumen,both(containsString(a).and(containsString(b);TestpublicvoidtestAssertThathasItemsContainsString
8、()org.junit.Assert.assertThat(Arrays.asList(one,two,three),hasItems(one,three);TestpublicvoidtestAssertThatEveryItemContainsString()org.junit.Assert.assertThat(Arrays.asList(newStringfun,ban,net),everyItem(containsString(n);/CoreHamcrestMatcherswithassertThatTestpublicvoidtestAssertThatHamcrestCoreM
9、atchers()assertThat(good,allOf(equalTo(good),startsWith(good);assertThat(good,not(allOf(equalTo(bad),equalTo(good);assertThat(good,anyOf(equalTo(bad),equalTo(good);assertThat(7,not(CombinableMatcher.either(equalTo(3).or(equalTo(4);assertThat(newObject(),not(sameInstance(newObject();package test;impo
10、rt static org.hamcrest.CoreMatchers.*;import static org.junit.Assert.*;import java.util.Arrays;import org.hamcrest.core.CombinableMatcher;import org.junit.Test;public class AssertTests Test public void testAssertArrayEquals() byte expected = trial.getBytes(); byte actual = trial.getBytes(); org.juni
11、t.Assert.assertArrayEquals(failure - byte arrays not same, expected, actual); Test public void testAssertEquals() org.junit.Assert.assertEquals(failure - strings not same, 5l, 5l); Test public void testAssertFalse() org.junit.Assert.assertFalse(failure - should be false, false); Test public void tes
12、tAssertNotNull() org.junit.Assert.assertNotNull(should not be null, new Object(); Test public void testAssertNotSame() org.junit.Assert.assertNotSame(should not be same Object, new Object(), new Object(); Test public void testAssertNull() org.junit.Assert.assertNull(should be null, null); Test publi
13、c void testAssertSame() Integer aNumber = Integer.valueOf(768); org.junit.Assert.assertSame(should be same, aNumber, aNumber); / JUnit Matchers assertThat Test public void testAssertThatBothContainsString() org.junit.Assert.assertThat(albumen, both(containsString(a).and(containsString(b); Test publi
14、c void testAssertThathasItemsContainsString() org.junit.Assert.assertThat(Arrays.asList(one, two, three), hasItems(one, three); Test public void testAssertThatEveryItemContainsString() org.junit.Assert.assertThat(Arrays.asList(new String fun, ban, net ), everyItem(containsString(n); / Core Hamcrest
15、Matchers with assertThat Test public void testAssertThatHamcrestCoreMatchers() assertThat(good, allOf(equalTo(good), startsWith(good); assertThat(good, not(allOf(equalTo(bad), equalTo(good); assertThat(good, anyOf(equalTo(bad), equalTo(good); assertThat(7, not(CombinableMatcher. either(equalTo(3).or
16、(equalTo(4); assertThat(new Object(), not(sameInstance(new Object(); 3. 核心注解3.1. 说明Before初始化方法After释放资源Test测试方法,在这里可以测试期望异常和超时时间Ignore忽略的测试方法BeforeClass针对所有测试,只执行一次,且必须为static voidAfterClass针对所有测试,只执行一次,且必须为static voidRunWith指定测试类使用某个运行器Parameters指定测试类的测试数据集合Rule允许灵活添加或重新定义测试类中的每个测试方法的行为FixMethodOrd
17、er指定测试方法的执行顺序3.2. 执行顺序一个测试类单元测试的执行顺序为:BeforeClass Before Test After AfterClass每一个测试方法的调用顺序为:Before Test After3.3. 示例java view plain copy print?packagetest;importstaticorg.junit.Assert.*;importorg.junit.*;publicclassJDemoTestBeforeClasspublicstaticvoidsetUpBeforeClass()throwsExceptionSystem.out.print
18、ln(inBeforeClass=);AfterClasspublicstaticvoidtearDownAfterClass()throwsExceptionSystem.out.println(inAfterClass=);Beforepublicvoidbefore()System.out.println(inBefore);Afterpublicvoidafter()System.out.println(inAfter);Test(timeout=10000)publicvoidtestadd()JDemoa=newJDemo();assertEquals(6,a.add(3,3);S
19、ystem.out.println(inTest-Add);Testpublicvoidtestdivision()JDemoa=newJDemo();assertEquals(3,a.division(6,2);System.out.println(inTest-Division);IgnoreTestpublicvoidtest_ignore()JDemoa=newJDemo();assertEquals(6,a.add(1,5);System.out.println(intest_ignore);Testpublicvoidteest_fail()fail();classJDemoext
20、endsThreadintresult;publicintadd(inta,intb)trysleep(1000);result=a+b;catch(InterruptedExceptione)returnresult;publicintdivision(inta,intb)returnresult=a/b;package test;import static org.junit.Assert.*;import org.junit.*;public class JDemoTest BeforeClass public static void setUpBeforeClass() throws
21、Exception System.out.println(in BeforeClass=); AfterClass public static void tearDownAfterClass() throws Exception System.out.println(in AfterClass=); Before public void before() System.out.println(in Before); After public void after() System.out.println(in After); Test(timeout = 10000) public void
22、testadd() JDemo a = new JDemo(); assertEquals(6, a.add(3, 3); System.out.println(in Test -Add); Test public void testdivision() JDemo a = new JDemo(); assertEquals(3, a.division(6, 2); System.out.println(in Test -Division); Ignore Test public void test_ignore() JDemo a = new JDemo(); assertEquals(6,
23、 a.add(1, 5); System.out.println(in test_ignore); Test public void teest_fail() fail(); class JDemo extends Thread int result; public int add(int a, int b) try sleep(1000); result = a + b; catch (InterruptedException e) return result; public int division(int a, int b) return result = a / b; 执行结果:pla
24、in view plain copy print?inBeforeClass=inBeforeinTest-AddinAfterinBeforeinTest-DivisioninAfterinAfterClass=in BeforeClass=in Beforein Test -Addin Afterin Beforein Test -Divisionin Afterin AfterClass=图中左上红框中部分表示Junit运行结果,5个成功(1个忽略),1个错误,1个失败。(注意错误和失败不是一回事,错误说明代码有错误,而失败表示该测试方法测试失败)左下红框中则表示出了各个测试方法的运行状态,可以看到成功、错误、失败、失败各自的图标是不一样的,还可以看到运行时间。右边部分则是异常堆栈,可查看异常信息。3.4. 实例总结3.4.1. 参数化测试有时一个测试方法,不同的参数值会产生不同的结果,那么我们为了测试全面,会把多个参数值都写出来并一一断言测试,这样有时难免费时费力,这是我们便可以采用参数化测试来解决这个问题。参数化测试就好比把一个“输入值,期望值”的集合传入给测试方法,达到一次性
copyright@ 2008-2022 冰豆网网站版权所有
经营许可证编号:鄂ICP备2022015515号-1