美文网首页JUnit 学习笔记
JUnit4 单元测试框架 学习笔记

JUnit4 单元测试框架 学习笔记

作者: 专职跑龙套 | 来源:发表于2017-01-24 12:44 被阅读121次

    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 官网

    相关文章

      网友评论

        本文标题:JUnit4 单元测试框架 学习笔记

        本文链接:https://www.haomeiwen.com/subject/uaezbttx.html