首页 » java

junit4 简易教程 一

   发表于:java评论 ()   热度:151

包引入

 

<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(假设)

Assume顾名思义是假设的意思也就是做一些假设,只有当假设成功后才会执行接下来的代码

使用Assumptions类中的假设方法时,当假设不成立时会报错,但是测试会显示被ignore忽略执行。也就是当我们一个类中有多个测试方法时,其中一个假设测试方法假设失败,其他的测试方法全部成功,那么该测试类也会显示测试成功! 这说明假设方法适用于:在不影响测试是否成功的结果的情况下根据不同情况执行相关代码!

看一下示例:

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

 

执行结果

 

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,更详细的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详细介绍: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));
    }
}

测试会执行所有的DataPoint, 如果任意一个assume失败,则该测试会被Ignore;任一 assert失败,则测试用例失败。

参数化测试
 

@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参数化测试更加简洁,后面再介绍

顺序执行

@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:按照某种确定但不可预测的顺序

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...]

(。・v・。)
喜欢这篇文章吗?欢迎分享到你的微博、QQ群,并关注我们的微博,谢谢支持。