1. 使用maven构建SpringBoot的名叫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>
<groupId>com.bjbs</groupId>
<artifactId>spring-boot-test</artifactId>
<version>0.0.1-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.13.RELEASE</version>
</parent>
<!-- 修改jdk版本 -->
<properties>
<java.version>1.8</java.version>
<!-- 指定thymeleaf和thymeleaf-layout-dialect高版本可以防止html标签不规范报错 -->
<thymeleaf.version>3.0.2.RELEASE</thymeleaf.version>
<thymeleaf-layout-dialect.version>2.0.4</thymeleaf-layout-dialect.version>
</properties>
<dependencies>
<!-- springBoot的启动器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 添加junit环境的jar包 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
</dependencies>
</project>
3. 新建UserDaoImpl.java
package com.bjbs.dao;
import org.springframework.stereotype.Repository;
@Repository
public class UserDaoImpl {
public void saveUser() {
System.out.println("insert into users......");
}
}
4. 新建UserServiceImpl.java
package com.bjbs.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.bjbs.dao.UserDaoImpl;
@Service
public class UserServiceImpl {
@Autowired
private UserDaoImpl userDaoImpl;
public void addUser() {
this.userDaoImpl.saveUser();
}
}
5. 新建App.java
package com.bjbs;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* SpringBoot启动类
*/
@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
6. 在src/test/java下, 新建UserServiceTest.java单元测试类
package com.bjbs.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 com.bjbs.App;
import com.bjbs.service.UserServiceImpl;
/**
*SpringBoot测试类
*@RunWith: 启动器
*SpringJUnit4ClassRunner.class: 让junit与spring环境进行整合
*
*@SpringBootTest(classes={App.class}) 1. 当前类为SpringBoot的测试类
*@SpringBootTest(classes={App.class}) 2. 加载SpringBoot启动类。
*
*junit与spring整合 @Contextconfiguartion("classpath:applicationContext.xml")
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes={App.class})
public class UserServiceTest {
@Autowired
private UserServiceImpl userServiceImpl;
@Test
public void testAddUser(){
this.userServiceImpl.addUser();
}
}
7. 选择单元测试方法名称, Run As-->Junit Test
8. 运行结果