Spring Boot Junit单元测试
SpringBoot Test集成测试
关于SpringJUnit4ClassRunner和SpringApplicationConfiguration不能引入的问题:
Spring Boot的SpringApplicationConfiguration注解在Spring Boot 1.4开始,被标记为Deprecated
解决:替换为SpringBootTest即可
http://blog.sina.com.cn/s/blog_70ae1d7b0102wfpt.html
加入依赖包
首先需要在pom.xml中加入junit依赖,其中scope限定了junit包的使用范围是test环境:
<!-- 添加junit4依赖 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<!-- 表示开发的时候引入,发布的时候不会加载此包 -->
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.0.2.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.0.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--这个依赖好像是必须加的,不然@SpringBootTest(classes = App.class)报错-->
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
</dependency>
选择需要测试的类,鼠标方法类名处Alt+Enter --> Create Test创建测试类,其中
@RunWith(SpringJUnit4ClassRunner.class) // SpringJUnit支持,由此引入Spring-Test框架支持!
@SpringApplicationConfiguration(classes = SpringBootSampleApplication.class) // 指定我们SpringBoot工程的Application启动类
@WebAppConfiguration // 由于是Web项目,Junit需要模拟ServletContext,因此我们需要给我们的测试类加上@WebAppConfiguration。
package com.jsptpd.zhywserver.dao;
import com.jsptpd.zhywserver.App;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.annotation.Resource;
/**
* Created by HASEE on 2017/11/10.
*/
@RunWith(SpringJUnit4ClassRunner.class) // SpringJUnit支持,由此引入Spring-Test框架支持!注:貌似加上这句启动不了????
@SpringApplicationConfiguration(classes = App.class) // 指定我们SpringBoot工程的Application启动类
public class HouseDesignMapperTest {
@Resource
HouseDesignMapper houseDesignMapper;
@Test
public void getHouseDesignName() throws Exception {
String houseDesignName = houseDesignMapper.getHouseDesignName("两房");
System.out.print(houseDesignName);
}
@Test
public void saveHouseDesignData() throws Exception {
}
@Test
public void updateHouseDesignData() throws Exception {
}
}
网友评论