spring boot 整合 junit 单元测试
1、创建项目(19-spring-boot-test)
2、pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.10.RELEASE</version>
</parent>
<groupId>cn.yangdh</groupId>
<artifactId>19-spring-boot-test</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>1.4.1.RELEASE</version>
</dependency>
</dependencies>
</project>
说明:本次使用的spring boot项目版本是1.5.10.RELEASE
注意事项:引入的 spring-boot-test 版本需要修改成1.4.1.RELEASE(1.4.0之后的、但是要低于spring boot项目的版本!!!@SpringBootTest 注解只有在spring-boot-test1.4.0之后才有!!!)不然 pom 文件报错。
3、直接编写(/src/main/java/cn/yangdh/dao/impl/UserDaoImpl.java)
package cn.yangdh.dao.impl;
import org.springframework.stereotype.Repository;
@Repository
public class UserDaoImpl {
public void saveUser(){
System.out.println("insert into users..");
}
}
4、直接编写(/src/main/java/cn/yangdh/service/impl/UserServiceImpl.java)
package cn.yangdh.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.yangdh.dao.impl.UserDaoImpl;
@Service
public class UserServiceImpl {
@Autowired
private UserDaoImpl userDao;
public void addUser(){
this.userDao.saveUser();
}
}
5、编写启动类(/src/main/java/cn/yangdh/App.java)
package cn.yangdh;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
6、编写测试类(/src/test/java/cn/yangdh/test/UserServiceTest.java)
package cn.yangdh.test;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import cn.yangdh.App;
import cn.yangdh.service.impl.UserServiceImpl;
/**
* Spring 测试类
* RunWith 该类是启动类、作用:就是让junt与spring环境进行整合。
* SpringBootTest(classes={App.class}) classes属性要的是数组类型、要的是启动器的类
含义1:被SpringBootTest 注解的当前类为 SpringBoot 的测试类
含义2:让SpringBootTest类去加载 SpringBoot 的启动器(也就是启动spring框架)
* @author *****
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes={App.class})//需要注意的是:该注解在Spring-Boot1.4.0以后才有
public class UserServiceTest {
@Autowired
private UserServiceImpl userServiceImpl; //
@Test
public void testAddUser(){ //测试Service层的addTest()方法
this.userServiceImpl.addUser();
}
}
7、run as - junit test 测试-成功