1 概述
本章节主要学习SpringBoot集成单元测试。
2 项目结构
2.1 pom文件
<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>2.1.3.RELEASE</version>
</parent>
<groupId>com.liulg</groupId>
<artifactId>10-spring-boot-junit</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<java.version>1.7</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--Junit测试依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
</dependencies>
</project>
2.2 Dao
package com.liulg.dao;
public interface UserDao {
public void saveUser();
}
2.3 DaoImpl
package com.liulg.dao.impl;
import org.springframework.stereotype.Repository;
import com.liulg.dao.UserDao;
@Repository
public class UserDaoImpl implements UserDao {
@Override
public void saveUser() {
System.out.println("insert user info .....");
}
}
2.4 Service
package com.liulg.service;
public interface UserService {
public void saveUser();
}
2.5 ServiceImpl
package com.liulg.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.liulg.dao.UserDao;
import com.liulg.service.UserService;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Override
public void saveUser() {
userDao.saveUser();
}
}
2.6 启动类
package com.liulg;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
2.7 测试类
package com.liulg.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.liulg.Application;
import com.liulg.service.UserService;
/**
* @RunWith:启动器,使junit与spring环境进行整合
* @SpringBootTest:指定当前类未springboot的测试类,
* 并根据classes属性加载Springboot启动类,启动Springboot。
* @Contextconfiguration("classpath:applicationContext.xml"):加载配置文件
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes= {Application.class})
public class UserServiceTest {
@Autowired
private UserService userService;
@Test
public void testSaveUser() {
userService.saveUser();
}
}