测试类"/>
Spring测试类
文章目录
- JUnit5
- 引入依赖
- 添加配置文件
- 添加java类
- 测试
- JUnit4
- 添加依赖
- 测试
JUnit5
引入依赖
<dependencies><!--spring context依赖--><!--当你引入Spring Context依赖之后,表示将Spring的基础依赖引入了--><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>6.0.2</version></dependency><!--spring对junit的支持相关依赖--><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>6.0.2</version></dependency><!--junit5测试--><dependency><groupId>org.junit.jupiter</groupId><artifactId>junit-jupiter-api</artifactId><version>5.9.0</version></dependency><!--log4j2的依赖--><dependency><groupId>org.apache.logging.log4j</groupId><artifactId>log4j-core</artifactId><version>2.19.0</version></dependency><dependency><groupId>org.apache.logging.log4j</groupId><artifactId>log4j-slf4j2-impl</artifactId><version>2.19.0</version></dependency>
</dependencies>
添加配置文件
beans.xml
开启注解扫描
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""xmlns:xsi=""xmlns:context=""xsi:schemaLocation=" .xsd .xsd"><context:component-scan base-package="com.atguigu.spring6.bean"/>
</beans>
添加java类
import org.springframework.stereotype.Component;@Component
public class User {public User() {System.out.println("run user");}
}
测试
//两种方式均可
//方式一
//@ExtendWith(SpringExtension.class)
//@ContextConfiguration("classpath:beans.xml")
//方式二
@SpringJUnitConfig(locations = "classpath:beans.xml")
public class SpringJUnit5Test {// 注解引入user类@Autowiredprivate User user;@Testpublic void testUser(){System.out.println(user);}
}
JUnit4
JUnit4在公司也会经常用到,在此也学习一下
添加依赖
<!-- junit测试 -->
<dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version>
</dependency>
测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:beans.xml")
public class SpringJUnit4Test {@Autowiredprivate User user;@Testpublic void testUser(){System.out.println(user);}
}
更多推荐
Spring测试类
发布评论