JUnit是一款优秀的开源Java单元测试框架,也是目前使用率最高最流行的测试框架。 主要被用来进行单元测试、白盒测试和集成测试。 本文主要介绍JUnit在SpringBoot中的使用

前提:加入JUnit 依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

使用JUnit进行单元测试

1. 基本使用

加入依赖之后,只需要在src/test/java/ 目录下编写测试文件即可进行单元测试,如:

@RunWith(SpringRunner.class)
@SpringBootTest
public class SimpleTest {
    @BeforeClass
    public static void setUpBeforeClass() throws Exception {
        System.out.println("this is beforeClass ...");
    }

    @AfterClass
    public static void tearDownAfterClass() throws Exception {
        System.out.println("this is afterClass ...");
    }

    @Before
    public void setUp() throws Exception {
        System.out.println("this is before....");
    }

    @After
    public void tearDown() throws Exception {
        System.out.println("this is after....");
    }

    @Test(timeout = 1000)
    public void test_method1() {
        System.out.println("this is test method1 ...");
        assertEquals(1, 1);
    }

    @Ignore
    @Test
    public void test_method2() {
        System.out.println("this is test method2 ...");
        String str = "hello";
        assertEquals("hello", str);
    }
}

其中:

2. 断言测试

断言测试也就是期望值测试,是单元测试的核心也就是决定测试结果的表达式,Assert对象中的断言方法: