我认为,能够对弹簧组件进行单元测试而无需使用临时测试配置加载完整的弹簧上下文,这是一个很大的优势,因为它干净,易于维护,编写速度更快,更改平滑。

实现此目标的一种方法是使用Mockito并告诉他用Mocks (或Spies)替换您要测试的类中的@Autowired组件。

这里举个例子。

我们有一个名为SalaryService的服务,它会根据传递的雇员ID来猜测是什么,从而计算出假设的净工资。 简单的概念。

协作者需要一项服务,第一个是EmployeeDAO,用于检索工资总额,第二个是TaxCalculator,用于根据工资总额应用一些税款。

package com.marco.springmockito;
import java.math.BigDecimal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class SalaryService {private static final BigDecimal minimumSalary = new BigDecimal(20000);@Autowiredprivate EmployeeDAO employeeDAO;@Autowiredprivate TaxCalculator taxCalculator;public BigDecimal getNetSalary(long employeeId) {BigDecimal netSalary = null;BigDecimal grossSalary = employeeDAO.getAnnualSalary(employeeId);BigDecimal taxes = taxCalculator.calculateTaxes(grossSalary);if (taxedSalaryIsGreaterThanMinimumSalary(grossSalary)) {netSalary = grossSalary.subtract(taxes);} else {netSalary = grossSalary;}return netSalary;}private boolean taxedSalaryIsGreaterThanMinimumSalary(BigDecimal taxedSalary) {return taxedSalary.compareTo(minimumSalary) == 1;}
}

EmployeeDAO是一项经典服务,负责从持久性存储中检索信息,并且看起来或多或少都是这样。

package com.marco.springmockito;
import java.math.BigDecimal;
import org.springframework.stereotype.Component;
@Component
public class EmployeeDAO {public BigDecimal getAnnualSalary(long employeeId) {// conncetTODB// run select for employeeId;return new BigDecimal(70000);}
}

TaxCalculator将需要TaxDao来检索税收信息,然后它将进行某种无聊且冗长的计算以退还税收。

package com.marco.springmockito;
import java.math.BigDecimal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class TaxCalculator {@Autowiredprivate TaxDao taxDao;public BigDecimal calculateTaxes(BigDecimal salary) {BigDecimal result = salary.multiply(taxDao.getTaxPercentageForYear(2014));// some other weird calculation ....return result;}
}

现在,我们要对SalaryService类进行单元测试。 我们不应被DAO和任何种类的数据库设置所困扰。 在此UNIT测试中,我们不在乎TaxCalculator在做什么。

我们想要的是测试我们的SalaryService行为是否符合预期,并且能够正确使用其协作者的工作。

这就是我们如何使用Mockito做到这一点。 我们用@InjectMocks标记要测试的类,并用@Mock标记其所有协作者(如果需要真正的实现,则标记@Spy )。

最后,我们需要在开始测试之前告诉我们的Unit框架,以操作所需的Mockito注入,然后使用
MockitoAnnotations。 initMocks(this);。

在测试中,我们需要模拟预期的操作,以便我们可以集中精力在SalaryService中要测试的实际逻辑上。

package com.marco.springmockito;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.when;
import java.math.BigDecimal;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
public class SalaryServiceTest {private static final long UserId = 123l;@InjectMocksprivate SalaryService salaryService;@Mockprivate EmployeeDAO employeeDAO;@Mockprivate TaxCalculator taxCalculator;@Beforepublic void init() {MockitoAnnotations.initMocks(this);}@Testpublic void testMinimumSalary() {BigDecimal annualSalary = new BigDecimal(10000);when(employeeDAO.getAnnualSalary(UserId)).thenReturn(annualSalary);when(taxCalculator.calculateTaxes(annualSalary)).thenReturn(new BigDecimal(1000));BigDecimal actual = salaryService.getNetSalary(UserId);assertThat(actual.compareTo(new BigDecimal(10000)), is(0));}@Testpublic void testMaximumSalary() {BigDecimal annualSalary = new BigDecimal(80000);when(employeeDAO.getAnnualSalary(UserId)).thenReturn(annualSalary);when(taxCalculator.calculateTaxes(annualSalary)).thenReturn(new BigDecimal(8000));BigDecimal actual = salaryService.getNetSalary(UserId);assertThat(actual.compareTo(new BigDecimal(72000)), is(0));}
}

它既简单又高效,希望对其他人有用。

参考:从我们的JCG合作伙伴 Marco Castigliego的Mockito中测试Spring组件,位于“ 删除重复并修复不良名称”博客中。

翻译自: https://www.javacodegeeks.com/2014/01/testing-spring-components-with-mockito.html

使用Mockito测试Spring组件相关推荐

  1. junit 测试 dao_JUnit测试Spring Service和DAO(带有内存数据库)

    junit 测试 dao 这篇文章描述了如何为Spring Web Application的Services和DAO实现JUnit测试. 它建立在Spring MVC-Service-DAO-Pers ...

  2. Mockito测试void方法会引发异常

    本文翻译自:Mockito test a void method throws an exception I have a method with a void return type. 我有一个vo ...

  3. VS2012创建ATL工程及使用MFC测试COM组件

    VS2012创建ATL工程及使用MFC测试COM组件 原创  2015年01月22日 16:23:21

  4. 使用 Jest 和 Enzyme 测试 React 组件

    type: FrontEnd title: Testing React components with Jest and Enzyme link: hackernoon.com/testing-rea ...

  5. Spring组件扫描context:component-scan/使用详解

    1.如果不想在xml文件中配置bean,我们可以给我们的类加上spring组件注解,只需再配置下spring的扫描器就可以实现bean的自动载入. <!-- 注解注入 --> <co ...

  6. spring 组件扫描_避免不必要的Spring配置组件扫描

    spring 组件扫描 我在堆栈溢出中遇到了一个有趣的问题. Brett Ryan有问题,Spring Security配置被初始化了两次. 当我查看他的代码时,我发现了问题所在. 让我展示显示代码. ...

  7. grep v grep_使用grep4j轻松测试分布式组件上的SLA

    grep v grep 因此,您的分布式体系结构如下图所示,您刚刚从企业那里收到了一项要求,以确保生产者发送并随后传输到下游系统(消费者)的消息的SLA必须快且永远不会慢于此. 400毫秒. 要求说: ...

  8. 使用Arquillian测试Spring Data + Spring Boot应用程序(第2部分)

    在上一篇文章中 ,我写了关于如何使用Arquillian Cube和 Docker一起测试Spring Data应用程序的信息. 测试看起来像: @RunWith(SpringRunner.class ...

  9. 使用grep4j轻松测试分布式组件上的SLA

    因此,您的分布式体系结构如下图所示,您刚刚从企业那里收到了一项要求,以确保生产者发送并随后传输到下游系统(消费者)的消息的SLA必须快且永远不会慢于此. 400毫秒. 要求说: 从生产者发送到任何消费 ...

最新文章

  1. Failed to register Grid Infrastructure type ora.mdns.type
  2. linux读写usb host,LINUX下USB1.1设备学习小记(3)_host与device
  3. 基于javaweb(springboot)城市地名地址信息管理系统设计和实现
  4. 安卓系统双屏异显_Android实现双屏异显
  5. Android控件——ListView之Adapter提供数据(其二)
  6. python培训价目表-python培训班费用在多少?
  7. 初步学习Django-第八篇:ORM常用操作
  8. 算法 后减前最大值,zt
  9. 杀掉移动设备幽灵启动
  10. 微信小程序反编译工具及方法
  11. 机器学习 数据预处理之特征编码(归纳整理版)
  12. centos yum
  13. 计算机fn的作用,fn是什么键 笔记本电脑fn键作用大全
  14. 7z文件格式及其源码的分析(四)
  15. C语言通过for循环控制计时,C语言中关于时间的函数
  16. JavaScript--轮播图_带计时器
  17. 小白Java学习之路(abstract抽象类,final,接口,equals)
  18. Conv2Former
  19. 工业互联网的基础技术有哪些
  20. NVIDIA之AI Course:Getting Started with AI on Jetson Nano—Class notes(二)

热门文章

  1. centos Error: Cannot find a valid baseurl for repo: base 解决方法
  2. JavaWeb核心常用API一览
  3. Tomcat6项目移到Tomcat7 提示 404 解决方案
  4. gradle配置_Gradle配置
  5. php cdi_通过MicroProfile上下文传播增强了CDI上下文和隔板
  6. bootstrap样式异常_处理异常功能样式
  7. java获得电脑性能_Java:使用SingletonStream获得性能
  8. java jdk 序列化_JDK 11:Java序列化的终结开始了吗?
  9. java api限流_Java 9:流API的增强
  10. gwt格式_GWT的渐进式Web应用程序配方