关于SpringBoot单元测试RunWith注解没有提示,无法解析,没有导包提示的问题,笔者在此说明一下。
首先说明一下项目的环境
IDE是IDEA
创建项目使用的是Spring Initializr工具
JDK环境是1.8
SpringBoot版本是
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.0</version>
<relativePath/>
</parent>
测试相关的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
笔者的测试类代码
package com.atguigu.delete;
import com.atguigu.delete.domain.Student;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
public class DeleteApplicationTests {
@Autowired
private Student student;
@Test
public void contextLoads() {
System.out.println(student);
}
}
直接运行测试方法
测试完成,输出正确。
明明没有写
@RunWith(SpringRunner.class)
注解为什么依然测试通过了呢
这是因为SpringBoot的高级版本使用junit5进行单元测试,无需RunWith注解即可进行测试。
应该是2.0及以上版本都是如此,至少2.4.0是如此。以后测试是不是更简单了呢
另外说下一些小问题
首先,使用Spring Initializr创建的项目
蓝色标注的文件或者文件夹可以删除,没什么用。
附上实体类和配置文件的代码
student.id=1
student.name=tomcat
student.gender=1
student.birth=2020/11/26
注意,如果没有配置日期格式化,日期的格式请按笔者的来
实体类代码
package com.atguigu.delete.domain;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.Date;
@ConfigurationProperties(prefix = "student")
@Component
public class Student {
private Integer id;
private String name;
private Integer gender;
private Date birth;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getGender() {
return gender;
}
public void setGender(Integer gender) {
this.gender = gender;
}
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
@Override
public String toString() {
return "Student[" +
"id=" + id +
", name=" + name +
", gender=" + gender +
", birth=" + birth +
']';
}
}
实体类代码没啥好说的,不要忘了注解
以上就是笔者对SpringBoot单元测试的说明,写的不好,请见谅