junit4 簡易教程

包引入

<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.12</version>
  <scope>test</scope>
</dependency> 

斷言

assertEquals("failure - strings are not equal", "text", "text");
assertArrayEquals("failure - byte arrays not same", expected, actual);
assertTrue("failure - should be true", true);
assertFalse("failure - should be false", false);
assertNull("should be null", null);
assertNotNull("should not be null", new Object());
assertSame("should be same", aNumber, aNumber);
assertNotSame("should not be same Object", new Object(), new Object());

Assume(假設(shè))

Assume顧名思義是假設(shè)的意思也就是做一些假設(shè),只有當(dāng)假設(shè)成功后才會執(zhí)行接下來的代碼

使用Assumptions類中的假設(shè)方法時汛蝙,當(dāng)假設(shè)不成立時會報錯,但是測試會顯示被ignore忽略執(zhí)行瘫证。也就是當(dāng)我們一個類中有多個測試方法時眼溶,其中一個假設(shè)測試方法假設(shè)失敗,其他的測試方法全部成功士嚎,那么該測試類也會顯示測試成功! 這說明假設(shè)方法適用于:在不影響測試是否成功的結(jié)果的情況下根據(jù)不同情況執(zhí)行相關(guān)代碼悔叽!

看一下示例:

    @Test
    public void next() {
        assumeTrue(false);
    }

執(zhí)行結(jié)果

org.junit.AssumptionViolatedException: got: <false>, expected: is <true>

    at com.meituan.meishi.filter.module.JunitTest.next(JunitTest.java:13)

Process finished with exit code 0

注意第一行:exit code 0,說明測試是通過的莱衩。

其api不再介紹,和assert完全一樣娇澎。

AssertThat&Matchers

assertThat([value], [matcher statement]);

以下僅介紹一些常用的Matcher,更詳細(xì)的API見:http://hamcrest.org/JavaHamcrest/javadoc/2.1/

多Macher

assertThat("myValue", allOf(startsWith("my"), containsString("Val")))//allof
assertThat("myValue", anyOf(startsWith("foo"), containsString("Val")))//anyof
assertThat("fab", both(containsString("a")).and(containsString("b")))//both
assertThat("fan", either(containsString("a")).and(containsString("b")))//attention:either...and
describedAs("a big decimal equal to %0", equalTo(myBigDecimal), myBigDecimal.toPlainString())//沒看懂干啥用的

集合(Iterable)
assertThat(Arrays.asList("bar", "baz"), everyItem(startsWith("ba")))//everyItem
assertThat(Arrays.asList("foo", "bar"), hasItem(startsWith("ba")))//hasItem
assertThat(Arrays.asList("foo", "bar", "baz"), hasItems("baz", "foo"))//hasItems
對象(Object)
assertThat(cheese, is(smelly))// is:cheese.equals(smelly)
assertThat(cheese, is(Cheddar.class))//is:instanceof
assertThat(cheese, isA(Cheddar.class))//isA:instanceof
assertThat(cheese, is(not(smelly)))//not:~is
assertThat(null, nullValue());//nullValue
assertThat(null, notNullValue());//notNullValue
assertThat("", theInstance(""));//同sameInstance
assertThat(a, sameInstance(a));//同一個對象
String
assertThat("myStringOfNote", containsString("ring"))//containsString
assertThat("myStringOfNote", startsWith("my"))//endWith
assertThat("myStringOfNote", endsWith("Note"))//startWith

異常

expected
    @Test(expected = IndexOutOfBoundsException.class)
    public void testException() {
        Lists.newArrayList().get(0);
    }
try-catch
    @Test
    public void testException() {
        try {
            Lists.newArrayList().get(0);
            fail("Unexpected: IndexOutboundException should be thrown");
        } catch (Exception e) {
            assertThat(e.getMessage(), is("Index: 0, Size: 0"));
        }
    }

@Rule

    @Rule
    public ExpectedException thrown = ExpectedException.none();

    @Test
    public void testException() {
        thrown.expect(IndexOutOfBoundsException.class);
        thrown.expectMessage("Index: 0, Size: 0");
        thrown.expectMessage(CoreMatchers.containsString("Size: 0"));//使用Matcher
        Lists.newArrayList().get(0);
    }
 * <ul>
 *   <li>{@link ErrorCollector}: collect multiple errors in one test method</li>
 *   <li>{@link ExpectedException}: make flexible assertions about thrown exceptions</li>
 *   <li>{@link ExternalResource}: start and stop a server, for example</li>
 *   <li>{@link TemporaryFolder}: create fresh files, and delete after test</li>
 *   <li>{@link TestName}: remember the test name for use during the method</li>
 *   <li>{@link TestWatcher}: add logic at events during method execution</li>
 *   <li>{@link Timeout}: cause test to fail after a set time</li>
 *   <li>{@link Verifier}: fail test if object state ends up incorrect</li>
 * </ul>
 *

rule詳細(xì)介紹:https://github.com/junit-team/junit4/wiki/Rules

@Ignore

@Ignore("Test is ignored as a demonstration")
@Test
public void testSame() {
    assertThat(1, is(1));
}

@TimeOut

測試運行時間

@Test(timeout=1000)
public void testWithTimeout() {
  ...
}

@Theory

@RunWith(Theories.class)
public class UserTest {
    @DataPoint
    public static String GOOD_USERNAME = "optimus";
    @DataPoint
    public static String USERNAME_WITH_SLASH = "optimus/prime";

    @Theory
    public void filenameIncludesUsername(String username) {
        assumeThat(username, not(containsString("/")));
        assertThat(new User(username).configFileName(), containsString(username));
    }
}

測試會執(zhí)行所有的DataPoint笨蚁, 如果任意一個assume失敗,則該測試會被Ignore趟庄;任一 assert失敗括细,則測試用例失敗。

參數(shù)化測試

@RunWith(ParameParameterizedterized.class)
public class Junit4Test {

    @Parameterized.Parameters
    public static Collection<Object[]> data() {
        return Arrays.asList(new Object[][] {
                { 0, 0 }, { 1, 1 }, { 2, 2}
        });
    }

    @Parameterized.Parameter(0)
    public int p1;
    @Parameterized.Parameter(1)
    public int p2;

    @Test
    public void testMatcher() {
        assertEquals(p1, p2);
    }
}

Junit5參數(shù)化測試更加簡潔戚啥,后面再介紹

順序執(zhí)行

@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class Junit4Test {
    @Test
    public void testC() {
        System.out.println("C");
    }

    @Test
    public void testA() {
        System.out.println("A");
    }

    @Test
    public void testB() {
        System.out.println("B");
    }
}
A
B
C

MethodSorters有三個成員:

  • NAME_ASCENDING:

  • JVM:虛擬機運行的順序奋单,每次順序都有可能不同

  • DEFAULT:按照某種確定但不可預(yù)測的順序

Suite&Category

這兩個組件是用來對多個TestClass進行組合或者分類測試;可以用在對單個module的歸類上猫十。

public class A {
  @Test
  public void a() {
    fail();
  }

  @Category(SlowTests.class)
  @Test
  public void b() {
  }
}

@Category({SlowTests.class, FastTests.class})
public class B {
  @Test
  public void c() {

  }
}

@RunWith(Categories.class)
@IncludeCategory(SlowTests.class)
@SuiteClasses( { A.class, B.class }) // Note that Categories is a kind of Suite
public class SlowTestSuite {
  // Will run A.b and B.c, but not A.a
}

@RunWith(Categories.class)
@IncludeCategory(SlowTests.class)
@ExcludeCategory(FastTests.class)
@SuiteClasses( { A.class, B.class }) // Note that Categories is a kind of Suite
public class SlowTestSuite {
  // Will run A.b, but not A.a or B.c
}

Runners

  • 代碼行運行

    org.junit.runner.JUnitCore.runClasses(TestClass1.class, ...);
    
  • 命令行運行

    java org.junit.runner.JUnitCore TestClass1 [...other test classes...]
    
  • Runners

    1. Suite

    2. Categories

    3. Parameterized

      ....

  • 第三方Runner

    1.SpringJUnit4ClassRunner

    2. MockitoJUnitRunner

    ......

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末览濒,一起剝皮案震驚了整個濱河市呆盖,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌贷笛,老刑警劉巖应又,帶你破解...
    沈念sama閱讀 217,185評論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異乏苦,居然都是意外死亡丁频,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,652評論 3 393
  • 文/潘曉璐 我一進店門邑贴,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人叔磷,你說我怎么就攤上這事拢驾。” “怎么了改基?”我有些...
    開封第一講書人閱讀 163,524評論 0 353
  • 文/不壞的土叔 我叫張陵繁疤,是天一觀的道長。 經(jīng)常有香客問我秕狰,道長稠腊,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,339評論 1 293
  • 正文 為了忘掉前任鸣哀,我火速辦了婚禮架忌,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘我衬。我一直安慰自己叹放,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,387評論 6 391
  • 文/花漫 我一把揭開白布挠羔。 她就那樣靜靜地躺著井仰,像睡著了一般。 火紅的嫁衣襯著肌膚如雪破加。 梳的紋絲不亂的頭發(fā)上俱恶,一...
    開封第一講書人閱讀 51,287評論 1 301
  • 那天,我揣著相機與錄音范舀,去河邊找鬼合是。 笑死,一個胖子當(dāng)著我的面吹牛尿背,可吹牛的內(nèi)容都是我干的端仰。 我是一名探鬼主播,決...
    沈念sama閱讀 40,130評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼田藐,長吁一口氣:“原來是場噩夢啊……” “哼荔烧!你這毒婦竟也來了吱七?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,985評論 0 275
  • 序言:老撾萬榮一對情侶失蹤鹤竭,失蹤者是張志新(化名)和其女友劉穎踊餐,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體臀稚,經(jīng)...
    沈念sama閱讀 45,420評論 1 313
  • 正文 獨居荒郊野嶺守林人離奇死亡吝岭,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,617評論 3 334
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了吧寺。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片窜管。...
    茶點故事閱讀 39,779評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖稚机,靈堂內(nèi)的尸體忽然破棺而出幕帆,到底是詐尸還是另有隱情,我是刑警寧澤赖条,帶...
    沈念sama閱讀 35,477評論 5 345
  • 正文 年R本政府宣布失乾,位于F島的核電站,受9級特大地震影響纬乍,放射性物質(zhì)發(fā)生泄漏碱茁。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,088評論 3 328
  • 文/蒙蒙 一仿贬、第九天 我趴在偏房一處隱蔽的房頂上張望纽竣。 院中可真熱鬧,春花似錦茧泪、人聲如沸退个。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,716評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽语盈。三九已至,卻和暖如春缰泡,著一層夾襖步出監(jiān)牢的瞬間刀荒,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,857評論 1 269
  • 我被黑心中介騙來泰國打工棘钞, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留缠借,地道東北人。 一個月前我還...
    沈念sama閱讀 47,876評論 2 370
  • 正文 我出身青樓宜猜,卻偏偏與公主長得像泼返,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子姨拥,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,700評論 2 354

推薦閱讀更多精彩內(nèi)容

  • JUnit Intro Android基于JUnit Framework來書寫測試代碼绅喉。JUnit是基于Java語...
    chandarlee閱讀 2,261評論 0 50
  • JUnit是一個編寫測試代碼的框架渠鸽,它是單元測試框架的xUnit體系結(jié)構(gòu)中的一個,目前主要使用的是JUnit 4 ...
    wangdy12閱讀 1,151評論 0 1
  • 初識Junit JUnit是一個測試框架柴罐,它使用注解來標(biāo)識指定測試的方法徽缚。JUnit是一個在Github上托管的開...
    一笑小先生閱讀 1,961評論 0 1
  • 一 JUnit介紹 JUnit是一個由Java語言編寫的開源的回歸測試框架,由Erich Gamma和Kent B...
    十丈_紅塵閱讀 1,747評論 0 4
  • 簡介 測試 在軟件開發(fā)中是一個很重要的方面,良好的測試可以在很大程度決定一個應(yīng)用的命運革屠。軟件測試中凿试,主要有3大種類...
    Whyn閱讀 5,753評論 0 2