JUnit5基本用法

先选中项目名称,单击右键,选择"New" -->"JUnite Test Case"(如图1),

在“New JUnit Test Case"窗口中,填写Test case的名字,可以选择要创建的方法(如图2)

JUnit5基本用法_第1张图片

图1,

JUnit5基本用法_第2张图片

图2

package test;

import static org.junit.jupiter.api.Assertions.*;

import java.util.ArrayList;
import java.util.Collection;

import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

class JUniteTest {
    private Collection collection;

    @BeforeAll
    static void setUpBeforeClass() throws Exception {
        // one-time initialization code
        System.out.println("@BeforeClass - oneTimeSetUp");
    }

    @AfterAll
    static void tearDownAfterClass() throws Exception {
        // one-time cleanup code
        System.out.println("@AfterClass - oneTimeTearDown");
    }

    @BeforeEach
    void setUp() throws Exception {
        collection = new ArrayList();
        System.out.println("@Before - setUp");
    }

    @AfterEach
    void tearDown() throws Exception {
        collection.clear();
        System.out.println("@After - tearDown");
    }

    @Test
    public void testEmptyCollection() {
        assertTrue(collection.isEmpty());
        System.out.println("@Test - testEmptyCollection");
    }

    @Test
    public void testOneItemCollection() {
        collection.add("itemA");
        assertEquals(1, collection.size());
        System.out.println("@Test - testOneItemCollection");
    }

}

运行结果:

@BeforeClass - oneTimeSetUp
@Before - setUp
@Test - testOneItemCollection
@After - tearDown
@Before - setUp
@Test - testEmptyCollection
@After - tearDown
@AfterClass - oneTimeTearDown

你可能感兴趣的:(JUnit)