SpringBoot使用@SpringBootTest注解開發(fā)單元測試教程
概述
@SpringBootTest注解是SpringBoot自1.4.0版本開始引入的一個用于測試的注解。基本用法如下:
1.添加依賴:
<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.cxh.test</groupId> <artifactId>generator</artifactId> <version>0.0.1-SNAPSHOT</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.1.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <!-- spring boot web 依賴 --> <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> </dependency> <!-- 修改后立即生效,熱部署 --> <dependency> <groupId>org.springframework</groupId> <artifactId>springloaded</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> </dependency> <!-- 視圖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <!-- mybatis 依賴 --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.0</version> </dependency> <!-- mysql 依賴 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.0.4</version> </dependency> <!-- alibaba的druid數(shù)據(jù)庫連接池 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.9</version> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>Camden.SR6</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <build/> </project>
2. 編寫啟動入口類
package com.cxh.study.platform; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * * @desciption * @author ChenXiHua * */ @SpringBootApplication public class GeneratorApp { /** * @param args */ public static void main(String[] args) { SpringApplication.run(GeneratorApp.class, args); } }
3. 編寫Controller類
package com.cxh.study.platform; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * * @desciption * @author ChenXiHua * */ @SpringBootApplication public class GeneratorApp { /** * @param args */ public static void main(String[] args) { SpringApplication.run(GeneratorApp.class, args); } }
4. 編寫service類
package com.cxh.study.platform.service; import java.util.List; import com.cxh.study.platform.entity.User; public interface IUserService { // 獲取所有用戶 List<User> getAll(); // 根據(jù)id獲取用戶 User getUserById(Integer id); }
package com.cxh.study.platform.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.cxh.study.platform.entity.User; import com.cxh.study.platform.mapper.IUserMapper; import com.cxh.study.platform.service.IUserService; @Service("userServiceImpl") public class UserServiceImpl implements IUserService { @Autowired private IUserMapper userMapper; @Override public List<User> getAll() { return userMapper.getAll(); } @Override public User getUserById(Integer id) { return userMapper.getUserById(id); } }
5. 編寫mapper類
package com.cxh.study.platform.mapper; import java.util.List; import org.apache.ibatis.annotations.Mapper; import com.cxh.study.platform.entity.User; @Mapper public interface IUserMapper { //獲取所有用戶 List<User>getAll(); //根據(jù)id獲取用戶 User getUserById(Integer id); }
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespace="com.cxh.study.platform.mapper.IUserMapper" > <!--獲取所有用戶 --> <select id="getAll" resultType="com.cxh.study.platform.entity.User"> SELECT * FROM s_user </select> <!-- 根據(jù)id獲取單個用戶 --> <select id="getUserById" parameterType="java.lang.Integer" resultType="com.cxh.study.platform.entity.User"> SELECT * FROM s_user where id=#{id} </select> </mapper>
6. 編寫測試類
package com.cxh.test; import java.net.URL; import java.util.List; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.embedded.LocalServerPort; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit4.SpringRunner; import com.cxh.study.platform.GeneratorApp; import com.cxh.study.platform.entity.User; /** * * @desciption 用戶管理測試類 * @author ChenXiHua * @date 2019年2月19日 * */ @RunWith(SpringRunner.class) @SpringBootTest(classes = GeneratorApp.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class UserTest { /** * @LocalServerPort 提供了 @Value("${local.server.port}") 的代替 */ @LocalServerPort private int port; private URL base; @Autowired private TestRestTemplate restTemplate; @Before public void setUp() throws Exception { String url = String.format("http://localhost:%d/", port); System.out.println(String.format("port is : [%d]", port)); this.base = new URL(url); } /** * 向"/test"地址發(fā)送請求,并打印返回結(jié)果 * @throws Exception */ //@Test public void test1() throws Exception { ResponseEntity<String> response = this.restTemplate.getForEntity( this.base.toString() + "/test", String.class, ""); System.out.println(String.format("測試結(jié)果為:%s", response.getBody())); } //@Test public void getAllTest() throws Exception { ResponseEntity<List> response = this.restTemplate.getForEntity( this.base.toString() + "/getAll", List.class, ""); System.out.println(String.format("測試結(jié)果為:%s", response.getBody())); } @Test public void getUserByIdTest() throws Exception { ResponseEntity<User> response = this.restTemplate.getForEntity( this.base.toString() + "/getUserById?id=1", User.class, ""); System.out.println(String.format("測試結(jié)果為:%s", response.getBody().toString())); } }
其中,classes屬性指定啟動類,SpringBootTest.WebEnvironment.RANDOM_PORT經(jīng)常和測試類中@LocalServerPort一起在注入屬性時使用。會隨機生成一個端口號。
7.測試結(jié)果:
2019-02-19 16:18:27.933 INFO 6676 --- [ main] com.cxh.test.UserTest : Started UserTest in 25.637 seconds (JVM running for 27.647)
port is : [14067]
2019-02-19 16:18:31.366 INFO 6676 --- [o-auto-1-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring FrameworkServlet 'dispatcherServlet'
2019-02-19 16:18:31.367 INFO 6676 --- [o-auto-1-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization started
2019-02-19 16:18:31.462 INFO 6676 --- [o-auto-1-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization completed in 95 ms
測試結(jié)果為:User [id=1, account=cxh, password=123, type=1, status=1]
2019-02-19 16:18:35.326 INFO 6676 --- [ Thread-5] ationConfigEmbeddedWebApplicationContext : Closing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@191004a: startup date [Tue Feb 19 16:18:05 CST 2019]; root of context hierarchy
到此這篇關于SpringBoot使用@SpringBootTest注解開發(fā)單元測試教程的文章就介紹到這了,更多相關SpringBoot使用@SpringBootTest開發(fā)單元測試內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Spring Boot使用線程池創(chuàng)建多線程的完整示例
在 Spring Boot 2 中,可以使用 @Autowired 注入 線程池(ThreadPoolTaskExecutor 或 ExecutorService),從而管理線程的創(chuàng)建和執(zhí)行,以下是使用 @Autowired 方式注入線程池的完整示例,感興趣的朋友一起看看吧2025-03-03SpringBoot+logback默認日志的配置和使用方式
這篇文章主要介紹了SpringBoot+logback默認日志的配置和使用方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-05-05淺談常用Java數(shù)據(jù)庫連接池(小結(jié))
這篇文章主要介紹了淺談常用Java數(shù)據(jù)庫連接池(小結(jié)),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-07-07java.lang.IllegalStateException異常解決
異常是程序在執(zhí)行過程中遇到的錯誤或異常情況,本文就來介紹一下java.lang.IllegalStateException異常解決,感興趣的可以了解一下2023-11-11Java?ArrayList集合之解鎖數(shù)據(jù)存儲新姿勢
這篇文章主要介紹了Java?ArrayList集合之解鎖數(shù)據(jù)存儲新姿勢,ArrayList是一個動態(tài)數(shù)組,可以自動調(diào)整大小,并提供了豐富的操作方法,文中通過代碼介紹的非常詳細,需要的朋友可以參考下2025-03-03基于springboot的RestTemplate、okhttp和HttpClient對比分析
這篇文章主要介紹了基于springboot的RestTemplate、okhttp和HttpClient對比分析,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-09-09