包引入
<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
Suite
Categories
-
Parameterized
....
-
第三方Runner
......