Junit4 Maven依赖

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

Junit4相关代码

切记使用注解时导包不要导错了

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.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration // 启动web运行环境 可有可无
@SpringBootTest(classes = { 启动类.class }) // 编写测试类
public class Hello_Junit {

    @Autowired
    private MongoTemplate mongoTemplatel;

    @Test
    public void test_function() {
        //TODO
    }
}

Junit5 Maven依赖

        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.3.22</version>
            <scope>test</scope>
        </dependency>

切记使用注解时导包不要导错了

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.context.web.WebAppConfiguration;

@ExtendWith(SpringExtension.class) // 使用Junit5测试工具
@WebAppConfiguration // 启动web运行环境
@SpringBootTest(classes = RunApplication.class) // 编写测试类
public class RunTest {

    @Autowired
    private User user;

    @Test
    public void testRun() {
        System.out.println(user);
    }
}

Junit4、5 均支持@BeforeEach、@AfterEach

注意官方文档说明:一次测试多个BeforeEach或AfterEach,无法预测其执行顺序,如方法名是doA(),不一定在doB()前执行!所以官方也说了:Junit团队在自己的测试中,最多有一个@BeforeEach或@AfterEach,除非每个测试方法没有依赖顺序关系!

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

    @BeforeEach
    void connectRedis2() {
        System.out.println("我是主测试方法前执行");
    }

    @Test
    void doTestHash() {
        System.out.println("我是主测试方法");
    }

    @AfterEach()
    void closeConnectRedis() {
        System.out.println("我是测试方法执行完毕才执行");
    }
特殊说明:
上述文章均是作者实际操作后产出。烦请各位,请勿直接盗用!转载记得标注原文链接:www.zanglikun.com
第三方平台不会及时更新本文最新内容。如果发现本文资料不全,可访问本人的Java博客搜索:标题关键字。以获取全部资料 ❤