JUnit4 单元测试框架 学习笔记

Assert 断言

具体的 API 参见 junit4 javadoc

  • static void assertArrayEquals() 接受不同的参数类型
  • static void assertEquals() 接受不同的参数类型
  • static void assertNotEquals() 接受不同的参数类型
  • static void assertTrue(boolean condition)
  • static void assertFalse(boolean condition)
  • static void assertNull(Object object)
  • static void assertNotNull(Object object)
  • static void assertSame(Object expected, Object actual)
  • static void assertNotSame(Object unexpected, Object actual)
  • static void assertThat(T actual, Matcher<? super T> matcher)

基本使用

使用 @Test 注解。

import org.junit.Test;
import static org.junit.Assert.*;

public class JUnit4_Test {

    @Test
    public void test1() {
        assertEquals(123, 123);
    }
}

assertThat 的使用

static void assertThat(T actual, Matcher<? super T> matcher):Asserts that actual satisfies the condition specified by matcher.

关于 matcher 的说明,参见 Java Hamcrest

示例如下:

import org.hamcrest.core.CombinableMatcher;
import org.junit.Test;

import java.util.Arrays;

import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.allOf;
import static org.hamcrest.CoreMatchers.anyOf;
import static org.hamcrest.CoreMatchers.both;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.everyItem;
import static org.hamcrest.CoreMatchers.hasItems;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.CoreMatchers.sameInstance;
import static org.hamcrest.CoreMatchers.startsWith;

public class JUnit4_Test {
    @Test
    public void testAssertThatBothContainsString() {
        assertThat("abc", both(containsString("a")).and(containsString("b")));
    }

    @Test
    public void testAssertThatHasItems() {
        assertThat(Arrays.asList("one", "two", "three"), hasItems("one", "three"));
    }

    @Test
    public void testAssertThatEveryItemContainsString() {
        assertThat(Arrays.asList(new String[]{"fun", "ban", "net"}), everyItem(containsString("n")));
    }

    // Core Hamcrest 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.<Integer>either(equalTo(3)).or(equalTo(4))));
        assertThat(new Object(), not(sameInstance(new Object())));
    }
}

测试用例的初始化

  • 类级别
    • @Before
    • @After
  • 方法级别
    • @BeforeClass 每一个 case 之前调用
    • @AfterClass 每一个 case 之后调用

示例如下:

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;

public class JUnit4_Test {
    private int i = 0;

    @Before
    public void init() {
        i = 10;
    }

    @After
    public void destroy() {
        i = 0;
    }

    @Test
    public void test1() {
        assertEquals(i, 10);
    }
}

测试用例的执行顺序

具体参见 Test execution order

By design, JUnit does not specify the execution order of test method invocations. Until now, the methods were simply invoked in the order returned by the reflection API. However, using the JVM order is unwise since the Java platform does not specify any particular order, and in fact JDK 7 returns a more or less random order. Of course, well-written test code would not assume any order, but some do, and a predictable failure is better than a random failure on certain platforms.
在设计上,JUnit 不指定 Test Case 的执行顺序。在运行时按照反射 API 返回的方法的顺序来执行,可能是随机的。另外,良好的测试代码不应该依赖于 Test Case 的执行顺序。

从 JUnit 4.11 开始,可以通过 @FixMethodOrder 注解来指定 Test Case 的执行顺序。

  • @FixMethodOrder(MethodSorters.DEFAULT):Sorts the test methods in a deterministic, but not predictable, order
  • @FixMethodOrder(MethodSorters.JVM):由 JVM 决定,在运行时按照反射 API 返回的方法的顺序来执行,可能是随机的
  • @FixMethodOrder(MethodSorters.NAME_ASCENDING)按照方法名升序的顺序执行

示例如下:

import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;

@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class TestMethodOrder {

    @Test
    public void testA() {
        System.out.println("first");
    }
    @Test
    public void testB() {
        System.out.println("second");
    }
    @Test
    public void testC() {
        System.out.println("third");
    }
}

测试用例的聚合 Aggregating tests in suites

具体参见 Aggregating tests in suites

使用 Suite 作为 Runner @RunWith(Suite.class),可以将多个类中的测试用例聚合以来,统一执行。

示例如下:

import org.junit.runner.RunWith;
import org.junit.runners.Suite;

@RunWith(Suite.class)
@Suite.SuiteClasses({
  TestFeatureLogin.class,
  TestFeatureLogout.class,
  TestFeatureNavigate.class,
  TestFeatureUpdate.class
})

public class FeatureTestSuite {
  // the class remains empty,
  // used only as a holder for the above annotations
}

异常的测试

具体参见 Exception testing

使用 @Test(expected = XX.class)
示例如下:

@Test(expected = IndexOutOfBoundsException.class)
public void test1() {
    List<String> l = new ArrayList<String>();
    l.get(1);
}

忽略某个测试用例

具体参见 Ignoring tests

使用 @Ignore 注解,例如:

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

超时的测试

具体参见 Timeout for tests

使用 @Test(timeout = 1000) 指定该测试用例允许运行的最长时间。
示例如下:该测试用例会 fail

@Test(timeout = 1000)
public void test1() throws Exception{
    int i = 1;

    Thread.sleep(2000);
}

规则 Rule 的使用

具体参见 Rules


引用:
JUnit4 官网

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,923评论 18 139
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,765评论 18 399
  • java笔记第一天 == 和 equals ==比较的比较的是两个变量的值是否相等,对于引用型变量表示的是两个变量...
    jmychou阅读 1,518评论 0 3
  • ​ 我时常游走在微博大道上,看看谁又上热搜了,看看美女帅哥,最近还多了每周一去看圆圆姐的微博评论,多是走马观花,有...
    有才华的老太太阅读 268评论 0 0
  • 年少时,父亲是座长青的高山,护佑我经过人生伊始的坎坷。 我记得,一年级期末,他撕掉了我小心翼翼贴在墙上的奖状。因为...
    小陈今天抱到月亮了么阅读 316评论 0 1