Spring Boot 单元测试示例

Spring 框架提供了一个专门的测试模块(spring-test),用于应用程序的单元测试。 在 Spring Boot 中,你可以通过spring-boot-starter-test启动器快速开启和使用它。

在pom.xml文件中引入maven依赖:

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-test</artifactId>

<scope>test</scope>

</dependency>

1. JUnit单元测试

当你的单元测试代码不需要用到 Spring Boot 功能,而只是一个简单的测试时,你可以直接编写你的 Junit 测试代码:

public class SimpleJunitTest {

@Test

public void testSayHi() {

System.out.println("Hi Junit.");

}

}

2. Spring Boot单元测试

当你的集成测试代码需要用到 Spring Boot 功能时,你可以使用@SpringBootTest注解。该注解是普通的 Spring 项目(非 Spring Boot 项目)中编写集成测试代码所使用的@ContextConfiguration注解的替代品。其作用是用于确定如何装载 Spring 应用程序的上下文资源。

@RunWith(SpringRunner.class)

@SpringBootTest

public class BeanInjectTest {

@Autowired

private HelloService helloService;

@Test

public void testSayHi() {

System.out.println(helloService.sayHi());

}

}

@Service

public class HelloService {

public String sayHi() {

return "--- Hi ---";

}

public String sayHello() {

return "--- Hello ---";

}

}

当运行 Spring Boot 应用程序测试时,它会自动的从当前测试类所在的包起一层一层向上搜索,直到找到一个@SpringBootApplication或@SpringBootConfiguration注释类为止。以此来确定如何装载 Spring 应用程序的上下文资源。

主配置启动类的代码为:

@SpringBootApplication

public class Application {

public static void main(String[] args) {

SpringApplication.run(Application.class);

}

}

如果搜索算法搜索不到你项目的主配置文件,将报出异常:

java.lang.IllegalStateException: Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=…) with your test

解决办法是,按 Spring Boot 的约定重新组织你的代码结构,或者手工指定你要装载的主配置文件:

@RunWith(SpringRunner.class)

@SpringBootTest(classes = {YourApplication.class})

public class BeanInjectTest {

// ...

}

基于 Spring 环境的 Junit 集成测试还需要使用@RunWith(SpringJUnit4ClassRunner.class)注解,该注解能够改变 Junit 并让其运行在 Spring 的测试环境,以得到 Spring 测试环境的上下文支持。否则,在 Junit 测试中,Bean 的自动装配等注解将不起作用。但由于 SpringJUnit4ClassRunner 不方便记忆,Spring 4.3 起提供了一个等同于 SpringJUnit4ClassRunner 的类 SpringRunner,因此可以简写成:@RunWith(SpringRunner.class)。

3. Spring MVC 单元测试

当你想对 Spring MVC 控制器编写单元测试代码时,可以使用@WebMvcTest注解。它提供了自配置的 MockMvc,可以不需要完整启动 HTTP 服务器就可以快速测试 MVC 控制器。

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;

import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.*;

import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

@RunWith(SpringRunner.class)

@WebMvcTest(HelloController.class)

public class HelloControllerTest {

@Autowired

private MockMvc mvc;

@Test

public void testHello() throws Exception {

mvc.perform(get("/hello"))

.andExpect(status().isOk())

.andDo(print());

}

}

@Controller

public class HelloController {

@GetMapping("/hello")

public String hello(ModelMap model) {

model.put("message", "Hello Page");

return "hello";

}

}

使用@WebMvcTest注解时,只有一部分的 Bean 能够被扫描得到,它们分别是:

@Controller

@ControllerAdvice

@JsonComponent

Filter

WebMvcConfigurer

HandlerMethodArgumentResolver

其他常规的@Component(包括@Service、@Repository等)Bean 则不会被加载到 Spring 测试环境上下文中。

如果测试的 MVC 控制器中需要@ComponentBean 的参与,你可以使用@MockBean注解来协助完成:

import static org.mockito.BDDMockito.*;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;

import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.*;

import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

@RunWith(SpringRunner.class)

@WebMvcTest(HelloController.class)

public class HelloControllerTest {

@Autowired

private MockMvc mvc;

@MockBean

private HelloService helloService;

@Test

public void testSayHi() throws Exception {

// 模拟 HelloService.sayHi() 调用, 返回 "=== Hi ==="

when(helloService.sayHi()).thenReturn("=== Hi ===");

mvc.perform(get("/hello/sayHi"))

.andExpect(status().isOk())

.andDo(print());

}

}

@Controller

public class HelloController {

@Autowired

private HelloService helloService;

@GetMapping("/hello/sayHi")

public String sayHi(ModelMap model) {

model.put("message", helloService.sayHi());

return "hello";

}

}

4. Spring Boot Web 单元测试

当你想启动一个完整的 HTTP 服务器对 Spring Boot 的 Web 应用编写测试代码时,可以使用@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)注解开启一个随机的可用端口。Spring Boot 针对 REST 调用的测试提供了一个 TestRestTemplate 模板,它可以解析链接服务器的相对地址。

@RunWith(SpringRunner.class)

@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)

public class ApplicationTest {

@Autowired

private TestRestTemplate restTemplate;

@Test

public void testSayHello() {

Map result = restTemplate.getForObject("/hello/sayHello", Map.class);

System.out.println(result.get("message"));

}

}

@Controller

public class HelloController {

@Autowired

private HelloService helloService;

@GetMapping("/hello/sayHello")

public @ResponseBody Object helloInfo() {

Map map = new HashMap<>();

map.put("message", helloService.sayHello());

return map;

}

}

原文地址:https://www.cnblogs.com/windpoplar/p/10921823.html

时间: 2024-08-06 14:10:47

Spring Boot 单元测试示例的相关文章

IDEA + Spring boot 单元测试

1. 创建测试类 打开IDEA,在任意类名,任意接口名上,按ctrl+shift+t选择Create New Test image 然后根据提示操作(默认即可),点击确认,就在项目的/test/java下的对应包里,生成了与类对应的测试类. 如果没有"Create New Test",请更新idea版本或者安装JUnitGenerator V2.0 1.1 安装JUnitGenerator V2.0 注意,本步骤是找不到那个"Create New Test",再做的

spring boot参考示例

库配置 <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>1

spring boot单元测试(转)

Junit这种老技术,现在又拿出来说,不为别的,某种程度上来说,更是为了要说明它在项目中的重要性.凭本人的感觉和经验来说,在项目中完全按标准都写Junit用例覆盖大部分业务代码的,应该不会超过一半. 刚好前段时间写了一些关于SpringBoot的帖子,正好现在把Junit再拿出来从几个方面再说一下,也算是给一些新手参考了. 那么先简单说一下为什么要写测试用例1. 可以避免测试点的遗漏,为了更好的进行测试,可以提高测试效率2. 可以自动测试,可以在项目打包前进行测试校验3. 可以及时发现因为修改代

spring mvc 单元测试示例

import java.awt.print.Printable; import java.io.IOException; import javax.servlet.http.HttpServletResponse; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired

Spring Boot单元测试

一个测试类包含下面两个注解: @RunWith(SpringRunner.class) @SpringBootTest 测试类中可直接注入接口: @Resource MyServerMgr myServerMgr; 在方法上加@Test表示它是个测试方法: @Test public void query() { String result = myServerMgr.query(); log.info("test query result is {}.", result); //使用断

Spring Boot的单元测试(Unit Test)

最近做了一些Spring Boot单元测试方面的东西,总结一下. 单元测试尽量要和Spring Boot框架减少耦合度,当你在测试某一项功能点是需要mock太多的对象时你就应该意识到这个功能点的耦合度太高了 使用Constructor Injection,不要使用Field Injection.这样才能更容易写单元测试代码.在Spring Framework 4.3以后,如果你只有一个Constructor, 就不再需要写@Autowired,Spring会默认他是autowire目标: pub

Spring Boot的单元测试(Unit Test)(一)

最近做了一些Spring Boot单元测试方面的东西,总结一下. 单元测试尽量要和Spring Boot框架减少耦合度,当你在测试某一项功能点是需要mock太多的对象时你就应该意识到这个功能点的耦合度太高了 使用Constructor Injection,不要使用Field Injection.这样才能更容易写单元测试代码.在Spring Framework 4.3以后,如果你只有一个Constructor, 就不再需要写@Autowired,Spring会默认他是autowire目标: pub

面试那点小事,你从未见过的spring boot面试集锦(附详细答案)

一, 什么是spring boot? 多年来,随着新功能的增加,spring变得越来越复杂.只需访问页面https://spring.io/projects,我们将看到所有在应用程序中使用的不同功能的spring项目.如果必须启动一个新的spring项目,我们必须添加构建路径或maven依赖项,配置application server,添加spring配置.因此,启动一个新的spring项目需要大量的工作,因为我们目前必须从头开始做所有事情.Spring Boot是这个问题的解决方案.Sprin

Spring Boot Ajax实例

本文将展示如何使用jQuery.ajax将HTML表单请求发送到Spring REST API并返回JSON响应. 使用的工具 : Spring Boot 1.5.1.RELEASE Spring 4.3.6.RELEASE Maven 3 jQuery Bootstrap 3 1. 项目结构 创建一个标准的Maven项目:ajax-example,用于演示在Spring Boot中使用Ajax技术,搜索用户信息.其结构如下图所示 - 2. 项目依赖 文件:pom.xml <?xml versi