import com.xzh.test.mapper.TeacherMapper;
import com.xzh.test.pojo.Teacher;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest//spring环境注解
public class Junit5Test {
    @Autowired
    private TeacherMapper teacherMapper;
    
    @Test
    public void test(){
        Teacher teacher = new Teacher();
        teacher.settName("name");
        teacher.settId("id");
        teacherMapper.insertTeacher(teacher);
        System.out.println("1");
    }
}
加上@SpringBootTest注解,才能在spring环境下测试,@Autowired自动注入才会生效
@Test使用的是Junit5的包中的注解(org.junit.jupiter.api.Test)
测试之后成功在数据库中插入数据
java.lang.IllegalStateException: Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=...) with your test
出现这种错误,有可能是因为测试类的启动类和正常的启动类不在同一个包中
详细情况看官网https://junit.org/junit5/docs/current/user-guide/#writing-tests-annotations
原文:https://www.cnblogs.com/xzh-hash/p/14546975.html