Juint版本说明
Maven的pom.xml中的依赖包
junit4:
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
junit5:
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.6.2</version>
<scope>test</scope>
</dependency>
scope属性讲解:
在上边的依赖中,两个依赖中都写了scope属性,那到底是什么意思呢?
先介绍一个标准的Maven项目结构。
scope为test表示依赖项目仅仅参与测试相关的工作,包括测试代码的编译,执行。比较典型的如junit。
test表示只能在src下的test文件夹下面才可以使用,你如果在a项目中引入了这个依赖,在b项目引入了a项目作为依赖,在b项目中这个注解不会生效,因为scope为test时无法传递依赖。
写Java代码的地方有两个src/main/java和src/test/java。如果不在依赖中添加scope为test属性,就可以在这两个文件夹下任意地方写@Test测试方法。但是如果添加了这个属性,就只能在src/test/java下写单元测试代码。
Spring项目中使用Junit
基于Maven构建的Spring项目,与普通Maven项目最大区别就是要加载Sprign容器。通常可以使用Spring提供的上下文ApplicationContext从配置文件或者配置类加载Spring容器。
public static void main(String[] args) {
//加载类路径下的spring文件夹中的spring配置文件
ApplicationContext ctx = new ClassPathXmlApplicationContext("spring/applicationContext.xml");
Student student = (Student) ctx.getBean("student");
System.out.println(student.getName());
}
其实还可以通过引入Spring相关的test依赖让其自动加载Spring上下文,这样就能利用如@Autowired这样的注解来自动注入从而获取bean了。
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
注意JUnit4和JUnit5写测试方法有些不同:
junit4:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring/applicationContext.xml"})
public class TestDemo {
@Resource
private Student student;
@Test
public void testStu(){
System.out.println(student.getName());
}
}
junit5:
@SpringJUnitConfig
//指定配置文件路径,会先从test域中找
@ContextConfiguration("spring/applicationContext.xml")
public class SpringTest {
@Resource
private Student student;
@Test
void testStu(){
System.out.println(student.getName());
}
}
两者都通过注解来加载Spring上下文从而能够获取spring容器中的对象。