mockito模拟依赖注入

Mockito @InjectMocks annotations allow us to inject mocked dependencies in the annotated class mocked object. This is useful when we have external dependencies in the class we want to mock. We can specify the mock objects to be injected using @Mock or @Spy annotations.

Mockito @InjectMocks批注允许我们将模拟的依赖项注入到带注释的类模拟对象中。 当我们要模拟的类中具有外部依赖项时,这很有用。 我们可以使用@Mock或@Spy批注指定要注入的模拟对象。

Mockito @InjectMocks (Mockito @InjectMocks)

Mockito tries to inject mocked dependencies using one of the three approaches, in the specified order.

Mockito尝试使用三种方法之一以指定的顺序注入模拟的依赖项。

  1. Constructor Based Injection – when there is a constructor defined for the class, Mockito tries to inject dependencies using the biggest constructor.基于构造函数的注入–当为该类定义了构造函数时,Mockito尝试使用最大的构造函数注入依赖项。
  2. Setter Methods Based – when there are no constructors defined, Mockito tries to inject dependencies using setter methods.基于Setter方法-当未定义构造函数时,Mockito尝试使用setter方法注入依赖项。
  3. Field Based – if there are no constructors or field-based injection possible, then mockito tries to inject dependencies into the field itself.基于字段的–如果没有可能的构造函数或基于字段的注入,则Mockito尝试将依赖项注入字段本身。

If there is only one matching mock object, then mockito will inject that into the object. If there is more than one mocked object of the same class, then mock object name is used to inject the dependencies.

如果只有一个匹配的模拟对象,则模拟将把它注入到对象中。 如果同一类的模拟对象不止一个,则使用模拟对象名称来注入依赖项。

模拟@InjectMocks示例 (Mock @InjectMocks Example)

Let’s create some services and classes with dependencies so that we can see Mockito dependency injection of mocks in action.

让我们创建一些具有依赖项的服务和类,以便我们可以看到Mockito依赖项在模拟中的依赖注入。

Service Classes

服务等级

package com.journaldev.injectmocksservices;public interface Service {public boolean send(String msg);
}
package com.journaldev.injectmocksservices;public class EmailService implements Service {@Overridepublic boolean send(String msg) {System.out.println("Sending email");return true;}}
package com.journaldev.injectmocksservices;public class SMSService implements Service {@Overridepublic boolean send(String msg) {System.out.println("Sending SMS");return true;}
}

App Service Classes with Dependencies

具有依赖关系的App Service类

package com.journaldev.injectmocksservices;//For Constructor Based @InjectMocks injection
public class AppServices {private EmailService emailService;private SMSService smsService;public AppServices(EmailService emailService, SMSService smsService) {this.emailService = emailService;this.smsService = smsService;}public boolean sendSMS(String msg) {return smsService.send(msg);}public boolean sendEmail(String msg) {return emailService.send(msg);}
}
package com.journaldev.injectmocksservices;//For Property Setter Based @InjectMocks injection
public class AppServices1 {private EmailService emailService;private SMSService smsService;public void setEmailService(EmailService emailService) {this.emailService = emailService;}public void setSmsService(SMSService smsService) {this.smsService = smsService;}public boolean sendSMS(String msg) {return smsService.send(msg);}public boolean sendEmail(String msg) {return emailService.send(msg);}}
package com.journaldev.injectmocksservices;//For Field Based @InjectMocks injection
public class AppServices2 {private EmailService emailService;private SMSService smsService;public boolean sendSMS(String msg) {return smsService.send(msg);}public boolean sendEmail(String msg) {return emailService.send(msg);}}

@InjectMocks构造函数注入示例 (@InjectMocks Constructor Injection Example)

package com.journaldev.mockito.injectmocks;import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;import com.journaldev.injectmocksservices.AppServices;
import com.journaldev.injectmocksservices.AppServices1;
import com.journaldev.injectmocksservices.AppServices2;
import com.journaldev.injectmocksservices.EmailService;
import com.journaldev.injectmocksservices.SMSService;class MockitoInjectMocksExamples extends BaseTestCase {@Mock EmailService emailService;@Mock SMSService smsService;@InjectMocks AppServices appServicesConstructorInjectionMock;@InjectMocks AppServices1 appServicesSetterInjectionMock;@InjectMocks AppServices2 appServicesFieldInjectionMock;@Testvoid test_constructor_injection_mock() {when(appServicesConstructorInjectionMock.sendEmail("Email")).thenReturn(true);when(appServicesConstructorInjectionMock.sendSMS(anyString())).thenReturn(true);assertTrue(appServicesConstructorInjectionMock.sendEmail("Email"));assertFalse(appServicesConstructorInjectionMock.sendEmail("Unstubbed Email"));assertTrue(appServicesConstructorInjectionMock.sendSMS("SMS"));}
}

Did you noticed that my test class is extending BaseTestCase. This is to initialize Mockito mocks before the tests, here is the code of the class.

您是否注意到我的测试类正在扩展BaseTestCase 。 这是在测试之前初始化Mockito模拟,这是该类的代码。

package com.journaldev.mockito.injectmocks;import org.junit.jupiter.api.BeforeEach;
import org.mockito.MockitoAnnotations;class BaseTestCase {@BeforeEachvoid init_mocks() {MockitoAnnotations.initMocks(this);}}

If you won’t call MockitoAnnotations.initMocks(this); then you will get NullPointerException.

如果您不致电MockitoAnnotations.initMocks(this); 那么您将获得NullPointerException

Also, I am using JUnit 5 to run the test cases. If you are not familiar with it, have a look at JUnit 5 Tutorial.

另外,我正在使用JUnit 5运行测试用例。 如果您不熟悉它,请查看JUnit 5 Tutorial 。

@InjectMocks设置器方法注入示例 (@InjectMocks Setter Methods Injection Example)

@Test
void test_setter_injection_mock() {when(appServicesSetterInjectionMock.sendEmail("New Email")).thenReturn(true);when(appServicesSetterInjectionMock.sendSMS(anyString())).thenReturn(true);assertTrue(appServicesSetterInjectionMock.sendEmail("New Email"));assertFalse(appServicesSetterInjectionMock.sendEmail("Unstubbed Email"));assertTrue(appServicesSetterInjectionMock.sendSMS("SMS"));}

@InjectMocks基于字段的注入示例 (@InjectMocks Field Based Injection Example)

@Test
void test_field_injection_mock() {when(appServicesFieldInjectionMock.sendEmail(anyString())).thenReturn(true);when(appServicesFieldInjectionMock.sendSMS(anyString())).thenReturn(true);assertTrue(appServicesFieldInjectionMock.sendEmail("Email"));assertTrue(appServicesFieldInjectionMock.sendEmail("New Email"));assertTrue(appServicesFieldInjectionMock.sendSMS("SMS"));}
GitHub Repository.GitHub存储库中查看完整的代码和更多Mockito示例。

Reference: API Doc

参考: API文档

翻译自: https://www.journaldev.com/21887/mockito-injectmocks-mocks-dependency-injection

mockito模拟依赖注入

mockito模拟依赖注入_Mockito @InjectMocks –模拟依赖注入相关推荐

  1. 什么是依赖注入 php,什么是依赖注入?

    译文首发于 什么是依赖注入,转载请注明出处. 本文是依赖注入(Depeendency Injection)系列教程的第一篇文章,本系列教程主要讲解如何使用 PHP 实现一个轻量级服务容器,教程包括: ...

  2. 依赖注入(di)模式_Java依赖注入– DI设计模式示例教程

    依赖注入(di)模式 Java Dependency Injection design pattern allows us to remove the hard-coded dependencies ...

  3. php 依赖注入框架,通过实现依赖注入和路由,构建一个自己的现代化PHP框架

    如何提高自己编写代码的能力呢?我们首先想到的是阅读学习优秀的开源项目,然后写一个自己的web框架或类库组件.作为web开发者,我们通常都是基于面向对象OOP来开发的,所以面向对象的设计能力或者说设计模 ...

  4. python依赖注入_什么是依赖注入?

    这篇文章是关于一般依赖关系注入和在PHP中实现依赖注入容器系列的第一部分. 今天我不会谈论容器然而我想以一些具体的示例介绍依赖注入的概念希望说明尝试去解决问题和它给开发者带来的好处.如果你已经知道依赖 ...

  5. php对象依赖注入作用,php面向对象依赖注入理解及代码举例分析解释

    依赖注入是通过类的构造函数.方法.或者直接写入的方式,将所依赖的组件传递给类的方式.一般通过构造函数注入的是强依赖关系的组件,setter方式用来注入可选的依赖组件. 现在,大多数流行的PHP框架都采 ...

  6. Spring依赖注入Bean为空,注入失效场景

    场景介绍 使用spring往一个bean(BeanB)注入另一个bean(BeanA),发现BeanA为null,注入失败了. 代码展示 /*** @author huangd* @date 2021 ...

  7. java中四种注入注解,Spring中依赖注入的四种方式

    在Spring容器中为一个bean配置依赖注入有三种方式: · 使用属性的setter方法注入  这是最常用的方式: · 使用构造器注入: · 使用Filed注入(用于注解方式). 使用属性的sett ...

  8. java什么是依赖注入_什么是依赖注入?

    转自 https://blog.csdn.net/coding_1994/article/details/80634810,这位作者写的很清晰. Spring 能有效地组织J2EE应用各层的对象.不管 ...

  9. 依赖注入原理(为什么需要依赖注入)

    0. 前言 在软件工程领域,依赖注入(Dependency Injection)是用于实现控制反转(Inversion of Control)的最常见的方式之一.本文主要介绍依赖注入原理和常见的实现方 ...

最新文章

  1. DeeCamp 2020 赛题大公开!快来看你想选哪个
  2. Win32 GetWindowLong函数实例Demo
  3. NYOJ 585 取石子(六)
  4. C语言实现字符串匹配的Rabin-Karp算法(附完整源码)
  5. 概率图模型中的变量消除顺序
  6. XCTF-MISC-新手区:pdf
  7. 在Google Cloud platform上的Kubernetes集群部署HANA Express
  8. java过滤器的原理_Java 三大器之过滤器(Filter)工作原理
  9. 关于高级导数的一个不等式估计
  10. html scale方法的作用,HTML Canvas scale() 方法
  11. 黑马程序员——选择排序
  12. 国庆海报设计适合哪些精品背景纹理?
  13. 为什么老是把词语读反_关于语言表达 6岁儿童经常把词语顺序念反
  14. 【FFMPEG系列】之工具调试:gprof性能分析
  15. 否认气候变暖的人都是睁眼说瞎话
  16. openstack安装配置(一)
  17. VMware安装linux镜像
  18. windows游戏编程:球球大作战(吃鸡版)源码
  19. 获取Adobe Flash 及Reader安装包
  20. ASP运行环境--.NetBox 软件使用方法,怎样使用.NETBOX运行asp项目?

热门文章

  1. 深入ASP.NET 2.0的提供者模型
  2. CSS 控件适配器的菜单样式解释
  3. [转载] python字符串分割
  4. SQL批量更新 关系表更新
  5. 第3章 文件操作-函数练习题
  6. Oracle 11g vs 12c 内存、优化器等默认参数对比
  7. Nginx启动/重启脚本详解
  8. AngularJS Slider指令(directive)扩展
  9. PostgreSQL一些简单问题以及解决办法
  10. Replace Record with Data Class