SpringBoot单元测试写法

156 阅读1分钟

SpringBoot单元测试写法

示例代码

import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoTest {

    @Autowired(required = false)
    JdbcTemplate jdbcTemplate;

    @Test
    public void test1() {
        Assert.assertNotNull("jdbcTemplate为null", jdbcTemplate);
    }

    @Test
    public void test2() {
    }

    @Before
    public void before1() {
        System.out.println("\n----- Before -----");
    }

    @After
    public void after1() {
        System.out.println("----- After -----\n");
    }
}

Maven依赖

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

<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <!-- <version>4.13.1</version> -->
    <scope>test</scope>
</dependency>