×
Spring Boot教程Spring Boot简介Spring Boot快速入门Spring Boot引导过程Spring Boot Tomcat部署Spring Boot构建系统Spring Boot代码结构Spring Boot Bean和依赖注入Spring Boot运行器(Runner)Spring Boot应用程序属性Spring Boot日志Spring Boot构建RESTful Web服务Spring Boot异常处理Spring Boot拦截器Spring Boot Servlet过滤器Spring Boot Tomcat端口号Spring Boot Rest模板Spring Boot文件处理Spring Boot服务组件Spring Boot Thymeleaf示例Spring Boot使用RESTful Web服务Spring Boot CORS支持Spring Boot国际化Spring Boot调度Spring Boot启用HTTPSSpring Boot Eureka服务器Spring Boost Eureka服务注册Spring Boot Zuul代理服务器和路由Spring Boot云配置服务器Spring Boot云配置客户端Spring Boot ActuatorSpring Boot管理服务器Spring Boot管理客户端Spring Boot启用Swagger2Spring Boot创建Docker镜像Spring Boot跟踪微服务日志Spring Boot Flyway数据库Spring Boot发送电子邮件Spring Boot HystrixSpring Boot Web SocketSpring Boot批量服务Spring Boot Apache KafkaSpring Boot单元测试用例Spring Boot Rest控制器单元测试Spring Boot数据库源(连接数据库)Spring Boot保护Web应用程序

Spring Boot单元测试用例


单元测试是开发人员为确保单个单元或组件功能正常工作而进行的测试之一。在本教程中,将了解和学习如何使用Mockito和Webrmrp编写单元测试用例。

Mockito

要将Mockito Mocks注入Spring Beans,需要在构建配置文件中添加Mockito-core依赖项。
Maven用户可以在pom.xml 文件中添加以下依赖项。

<dependency>
   <groupId>org.mockito</groupId>
   <artifactId>mockito-core</artifactId>
   <version>2.13.0</version>
</dependency>
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-test</artifactId>
   <scope>test</scope>
</dependency>

Gradle用户可以在build.gradle 文件中添加以下依赖项。

compile group: 'org.mockito', name: 'mockito-core', version: '2.13.0'
testCompile('org.springframework.boot:spring-boot-starter-test')

此处给出了编写Service类的代码,该类包含一个返回String值的方法。

package com.yiibai.mockitodemo;

import org.springframework.stereotype.Service;

@Service
public class ProductService {
   public String getProductName() {
      return "Honey";
   } 
}

现在,将ProductService类注入另一个Service类文件,如图所示。

package com.yiibai.mockitodemo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class OrderService {
   @Autowired
   ProductService productService;

   public OrderService(ProductService productService) {
      this.productService = productService;
   }
   public String getProductName() {
      return productService.getProductName();
   }
}

主 Spring Boot应用程序类文件如下 -

package com.yiibai.mockitodemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class MockitoDemoApplication {
   public static void main(String[] args) {
      SpringApplication.run(MockitoDemoApplication.class, args);
   }
}

然后,要测试配置应用程序上下文。 就将@Profile("test")注释用于在测试用例运行时配置类。

package com.yiibai.mockitodemo;

import org.mockito.Mockito;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Profile;

@Profile("test")
@Configuration
public class ProductServiceTestConfiguration {
   @Bean
   @Primary
   public ProductService productService() {
      return Mockito.mock(ProductService.class);
   }
}

现在,可以在src/test/java/com/yiibai/mockitodemo包下为 OrderService 编写单元测试用例。

package com.yiibai.mockitodemo;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@SpringBootTest
@ActiveProfiles("test")
@RunWith(SpringJUnit4ClassRunner.class)
public class MockitoDemoApplicationTest {
   @Autowired
   private OrderService orderService;

   @Autowired
   private ProductService productService;

   @Test
   public void whenUserIdIsProvided_thenRetrievedNameIsCorrect() {
      Mockito.when(productService.getProductName()).thenReturn("Mock Product Name");
      String testName = orderService.getProductName();
      Assert.assertEquals("Mock Product Name", testName);
   }
}

下面给出了构建配置文件的完整代码。

Maven构建文件 - pom.xml

<?xml version = "1.0" encoding = "UTF-8"?>
<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.yiibai</groupId>
   <artifactId>mockito-demo</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <packaging>jar</packaging>

   <name>mockito-demo</name>
   <description>Demo project for Spring Boot</description>

   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>1.5.9.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>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter</artifactId>
      </dependency>
      <dependency>
         <groupId>org.mockito</groupId>
         <artifactId>mockito-core</artifactId>
         <version>2.13.0</version>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-test</artifactId>
         <scope>test</scope>
      </dependency>
   </dependencies>

   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
         </plugin>
      </plugins>
   </build>

</project>

Gradle构建文件 - build.gradle

buildscript {
   ext {
      springBootVersion = '1.5.9.RELEASE'
   }
   repositories {
      mavenCentral()
   }
   dependencies {
      classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
   }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'

group = 'com.yiibai'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
   mavenCentral()
}
dependencies {
   compile('org.springframework.boot:spring-boot-starter')
   compile group: 'org.mockito', name: 'mockito-core', version: '2.13.0'
   testCompile('org.springframework.boot:spring-boot-starter-test')
}

创建可执行的JAR文件,并使用以下Maven或Gradle1命令运行Spring Boot应用程序。

对于Maven,可以使用如下所示的命令 -

mvn clean install

在控制台窗口中查看测试结果,如下所示:

Results :

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0

对于Gradle,可以使用如下命令 -

gradle clean build

得到结果如下:


分类导航

关注微信下载离线手册

bootwiki移动版 bootwiki
(群号:472910771)