在Spring中可以使用junit配合注解进行单元测试
零、添加jar包:
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
</dependency>
一、常用注解
1、@RunWith(SpringJUnit4ClassRunner.class),让测试运行于spring测试环境
2、@ContextConfiguration 用来指定加载的Spring配置文件的位置,会加载默认配置文件,
@ContextConfiguration 注解有以下两个常用的属性:
locations:可以通过该属性手工指定 Spring 配置文件所在的位置,可以指定一个或多个 Spring 配置文件用,分开。
inheritLocations:是否要继承父测试用例类中的 Spring 配置文件,默认为 true。
二、常用方法
1、assertEquals(Object expected, Object actual)
比较两者是否相等
2. assertTrue(boolean condition)
比较参数是否为 true
三、配置文件:
可以在 测试类中添加注解,引用已有的配置文件 :
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:spring-mvc.xml","classpath:spring-mybatis.xml"})
也可以在项目的 src/test/resources文件夹下, 新增测试专用的配置文件,再引用:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath*:spring-test-service.xml")
spring-test-service.xml 如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 引入src/main/resources 已有的配置文件 -->
<!-- 以下的 META-INF/spring 是resuource文件夹下的xml文件的路径,如果是其他的文件名,自行修改 -->
<import resource="classpath*:META-INF/spring/*.xml"/>
<!-- support message international -->
<aop:aspectj-autoproxy/>
</beans>
四、示例代码 (仅显示测试代码,xml配置、Service层代码略)
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:spring-mvc.xml","classpath:spring-mybatis.xml"})
public class UserServiceImplTest {
@Autowired
private UserServiceImpl userService;
@Before
public void before() throws Exception {
}
@After
public void after() throws Exception {
}
@Test
public void testGetUserById() throws Exception {
//TODO: Test goes here...
Assert.assertEquals( "lin" , userService.getUserById(2).getUserName());
}
}
SpringBoot单元测试,详情见: https://www.cnblogs.com/expiator/p/8651045.html