首页 > 编程语言 >Java Mockito 快速入门指南 Mock是指使用Mockito创建的模拟对象,它模拟真实对象的行为,用于替代真实对象的依赖项,以便进行独立的单元测试

Java Mockito 快速入门指南 Mock是指使用Mockito创建的模拟对象,它模拟真实对象的行为,用于替代真实对象的依赖项,以便进行独立的单元测试

时间:2023-12-07 18:34:09浏览次数:37  
标签:account 对象 Mockito 注解 方法 模拟

Java Mockito 快速入门指南 Mock是指使用Mockito创建的模拟对象,它模拟真实对象的行为,用于替代真实对象的依赖项,以便进行独立的单元测试

在软件开发中,单元测试对于确保代码的正确性和可靠性至关重要。Mockito是一个强大的Java测试框架,它提供了丰富的功能和方法,使得编写模拟测试变得简单而高效。本文将介绍Mockito的基础使用方法,包括常用的方法和注解,并通过两个简单到困难的示例演示其用法。

常用方法

当使用Mockito进行单元测试时,以下是几个常用的Mockito方法和概念:

  • mock()/@Mock

    • Mock是指使用Mockito创建的模拟对象,它模拟真实对象的行为,用于替代真实对象的依赖项,以便进行独立的单元测试。
  • spy()/@Spy

    • Spy是指使用Mockito创建的部分模拟对象,它保留了真实对象的部分行为。Spy对象既可以模拟方法的返回值,也可以保留方法的实际行为。
  • @InjectMocks

    • @InjectMocks是一个Mockito注解,用于自动将模拟对象注入到被测对象中的相应字段中。
  • doReturn()

    • doReturn()方法用于为模拟对象设置方法调用的返回值,可以覆盖默认行为。
  • when()

    • when()方法用于指定模拟对象的方法调用,并设置相应的操作,例如返回值、异常等。
  • verify()

    • verify()方法用于验证模拟对象的方法是否被调用,并可以进一步验证方法的调用次数和参数。
  • Stub

    • Stub翻译成打桩,是指为模拟对象设置预定义的行为或返回值,使其在测试过程中按照期望的方式运行。

调用方式

在Mockito中,可以通过函数调用和注解两种方式来应用模拟对象。这两种方式在语法和使用上略有不同,下面将介绍它们的应用区别:

函数调用方式

使用函数调用方式,需要手动创建和管理模拟对象。
通过调用Mockito.mock()方法创建模拟对象,并使用各种when()、thenReturn()、verify()等函数来定义模拟对象的行为和验证。
函数调用方式更加灵活,可以在测试方法的任意位置创建和配置模拟对象。
示例代码:

List<String> mockedList = Mockito.mock(List.class);
Mockito.when(mockedList.get(0)).thenReturn("Mocked Value");
String result = mockedList.get(0);
Mockito.verify(mockedList).get(0);

注解方式

使用注解方式,可以通过注解来自动创建和注入模拟对象。
使用@Mock注解在测试类中声明模拟对象的字段,然后使用@InjectMocks注解将模拟对象自动注入到被测对象中。
注解方式更加简洁和便捷,省去了手动创建和配置模拟对象的步骤。

  • 需要注意,通过注解的方式,需要在 @Before test前显示声明 MockitoAnnotations.initMocks(this);

示例代码:

public class MyTestClass {
    @Mock
    private List<String> mockedList;
<span class="token annotation punctuation">@InjectMocks</span>
<span class="token keyword">private</span> <span class="token class-name">MyClass</span> myClass<span class="token punctuation">;</span>

<span class="token annotation punctuation">@Before</span>
<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">setup</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token class-name">MockitoAnnotations</span><span class="token punctuation">.</span><span class="token function">initMocks</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>

<span class="token annotation punctuation">@Test</span>
<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">testMethod</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token class-name">Mockito</span><span class="token punctuation">.</span><span class="token function">when</span><span class="token punctuation">(</span>mockedList<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">thenReturn</span><span class="token punctuation">(</span><span class="token string">"Mocked Value"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token class-name">String</span> result <span class="token operator">=</span> myClass<span class="token punctuation">.</span><span class="token function">myMethod</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token class-name">Mockito</span><span class="token punctuation">.</span><span class="token function">verify</span><span class="token punctuation">(</span>mockedList<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>

}

使用方法1

上面只是做了一个简单的介绍,下面我们结合一些例子来看看如何使用。

我们将创建一个示例来测试一个银行应用中的账户服务。假设我们有一个AccountService类,它依赖于AccountRepositoryNotificationService来执行一些操作。我们将使用Mockito来模拟这些依赖项,并测试AccountService的方法。

首先,让我们创建一个名为AccountService的类:

public class AccountService {
    private AccountRepository accountRepository;
    private NotificationService notificationService;
<span class="token keyword">public</span> <span class="token class-name">AccountService</span><span class="token punctuation">(</span><span class="token class-name">AccountRepository</span> accountRepository<span class="token punctuation">,</span> <span class="token class-name">NotificationService</span> notificationService<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span>accountRepository <span class="token operator">=</span> accountRepository<span class="token punctuation">;</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span>notificationService <span class="token operator">=</span> notificationService<span class="token punctuation">;</span>
<span class="token punctuation">}</span>

<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">deposit</span><span class="token punctuation">(</span><span class="token class-name">String</span> accountId<span class="token punctuation">,</span> <span class="token keyword">double</span> amount<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token class-name">Account</span> account <span class="token operator">=</span> accountRepository<span class="token punctuation">.</span><span class="token function">findById</span><span class="token punctuation">(</span>accountId<span class="token punctuation">)</span><span class="token punctuation">;</span>
    account<span class="token punctuation">.</span><span class="token function">deposit</span><span class="token punctuation">(</span>amount<span class="token punctuation">)</span><span class="token punctuation">;</span>
    accountRepository<span class="token punctuation">.</span><span class="token function">save</span><span class="token punctuation">(</span>account<span class="token punctuation">)</span><span class="token punctuation">;</span>
    notificationService<span class="token punctuation">.</span><span class="token function">sendNotification</span><span class="token punctuation">(</span><span class="token string">"Deposit successful"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>

}

接下来,我们将创建一个名为AccountRepository的接口和一个名为NotificationService的接口作为依赖项:

public interface AccountRepository {
    Account findById(String accountId);
<span class="token keyword">void</span> <span class="token function">save</span><span class="token punctuation">(</span><span class="token class-name">Account</span> account<span class="token punctuation">)</span><span class="token punctuation">;</span>

}

public interface NotificationService {
void sendNotification(String message);
}

然后,我们编写一个测试类AccountServiceTest,使用Mockito来模拟AccountRepositoryNotificationService,并测试AccountServicedeposit()方法。

import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;

public class AccountServiceTest {

<span class="token annotation punctuation">@Test</span>
<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">testDeposit</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token comment">// 创建模拟对象</span>
    <span class="token class-name">AccountRepository</span> accountRepositoryMock <span class="token operator">=</span> <span class="token class-name">Mockito</span><span class="token punctuation">.</span><span class="token function">mock</span><span class="token punctuation">(</span><span class="token class-name">AccountRepository</span><span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token class-name">NotificationService</span> notificationServiceMock <span class="token operator">=</span> <span class="token class-name">Mockito</span><span class="token punctuation">.</span><span class="token function">mock</span><span class="token punctuation">(</span><span class="token class-name">NotificationService</span><span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    
    <span class="token comment">// 创建被测对象并注入模拟对象</span>
    <span class="token class-name">AccountService</span> accountService <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">AccountService</span><span class="token punctuation">(</span>accountRepositoryMock<span class="token punctuation">,</span> notificationServiceMock<span class="token punctuation">)</span><span class="token punctuation">;</span>
    
    <span class="token comment">// 创建模拟账户</span>
    <span class="token class-name">Account</span> account <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Account</span><span class="token punctuation">(</span><span class="token string">"1234567890"</span><span class="token punctuation">,</span> <span class="token number">1000.0</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    
    <span class="token comment">// 设置模拟对象的行为</span>
    <span class="token class-name">Mockito</span><span class="token punctuation">.</span><span class="token function">when</span><span class="token punctuation">(</span>accountRepositoryMock<span class="token punctuation">.</span><span class="token function">findById</span><span class="token punctuation">(</span><span class="token string">"1234567890"</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">thenReturn</span><span class="token punctuation">(</span>account<span class="token punctuation">)</span><span class="token punctuation">;</span>
    
    <span class="token comment">// 调用被测方法</span>
    accountService<span class="token punctuation">.</span><span class="token function">deposit</span><span class="token punctuation">(</span><span class="token string">"1234567890"</span><span class="token punctuation">,</span> <span class="token number">500.0</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    
    <span class="token comment">// 验证结果</span>
    <span class="token class-name">Assert</span><span class="token punctuation">.</span><span class="token function">assertEquals</span><span class="token punctuation">(</span><span class="token number">1500.0</span><span class="token punctuation">,</span> account<span class="token punctuation">.</span><span class="token function">getBalance</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token number">0.01</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    
    <span class="token comment">// 验证模拟对象的方法是否被调用</span>
    <span class="token class-name">Mockito</span><span class="token punctuation">.</span><span class="token function">verify</span><span class="token punctuation">(</span>accountRepositoryMock<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">save</span><span class="token punctuation">(</span>account<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token class-name">Mockito</span><span class="token punctuation">.</span><span class="token function">verify</span><span class="token punctuation">(</span>notificationServiceMock<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">sendNotification</span><span class="token punctuation">(</span><span class="token string">"Deposit successful"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>

}

在这个示例中,我们首先使用Mockito.mock()方法创建了一个名为accountRepositoryMock的模拟对象和一个名为notificationServiceMock的模拟对象。然后,我们创建了AccountService的实例,并使用模拟对象进行依赖项注入。

接下来,我们创建了一个名为account的模拟账户,并使用Mockito.when().thenReturn()方法为模拟对象的findById()方法设置了存根,以返回模拟账户。然后,我们调用accountService.deposit()方法进行测试,并使用Assert.assertEquals()方法验证账户的余额是否正确更新。

最后,我们使用Mockito.verify()方法验证模拟对象的save()方法和sendNotification()方法是否被调用。

通过这个示例,我们演示了如何使用Mockito的函数调用方式进行复杂的模拟测试。使用Mockito的各种函数,我们可以方便地设置模拟对象的行为、验证方法的调用,并确保被测代码的正确性。

使用方法2

当使用Spring Boot进行开发时,我们经常会使用 @Component 或者 @Autowired 的方式进行开发,下面介绍如何使用Mockito和注解的方式来对带有依赖注入的Spring组件进行测试。

下面是一个示例,展示了如何使用Mockito和注解对带有依赖注入的AccountService进行测试。

首先,让我们定义AccountService类并添加@Component注解:

@Component
public class AccountService {
    @Autowired
    private AccountRepository accountRepository;
    @Autowired
    private NotificationService notificationService;
<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">deposit</span><span class="token punctuation">(</span><span class="token class-name">String</span> accountId<span class="token punctuation">,</span> <span class="token keyword">double</span> amount<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token class-name">Account</span> account <span class="token operator">=</span> accountRepository<span class="token punctuation">.</span><span class="token function">findById</span><span class="token punctuation">(</span>accountId<span class="token punctuation">)</span><span class="token punctuation">;</span>
    account<span class="token punctuation">.</span><span class="token function">deposit</span><span class="token punctuation">(</span>amount<span class="token punctuation">)</span><span class="token punctuation">;</span>
    accountRepository<span class="token punctuation">.</span><span class="token function">save</span><span class="token punctuation">(</span>account<span class="token punctuation">)</span><span class="token punctuation">;</span>
    notificationService<span class="token punctuation">.</span><span class="token function">sendNotification</span><span class="token punctuation">(</span><span class="token string">"Deposit successful"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>

}

接下来,我们将编写一个名为AccountServiceTest的测试类,使用Mockito和注解对AccountService进行测试。

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;

@RunWith(MockitoJUnitRunner.class)
public class AccountServiceTest {
@Mock
private AccountRepository accountRepositoryMock;

<span class="token annotation punctuation">@Mock</span>
<span class="token keyword">private</span> <span class="token class-name">NotificationService</span> notificationServiceMock<span class="token punctuation">;</span>

<span class="token annotation punctuation">@InjectMocks</span>
<span class="token keyword">private</span> <span class="token class-name">AccountService</span> accountService<span class="token punctuation">;</span>

<span class="token annotation punctuation">@Test</span>
<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">testDeposit</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token comment">// 创建模拟账户</span>
    <span class="token class-name">Account</span> account <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Account</span><span class="token punctuation">(</span><span class="token string">"1234567890"</span><span class="token punctuation">,</span> <span class="token number">1000.0</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    
    <span class="token comment">// 设置模拟对象的行为</span>
    <span class="token class-name">Mockito</span><span class="token punctuation">.</span><span class="token function">when</span><span class="token punctuation">(</span>accountRepositoryMock<span class="token punctuation">.</span><span class="token function">findById</span><span class="token punctuation">(</span><span class="token string">"1234567890"</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">thenReturn</span><span class="token punctuation">(</span>account<span class="token punctuation">)</span><span class="token punctuation">;</span>
    
    <span class="token comment">// 调用被测方法</span>
    accountService<span class="token punctuation">.</span><span class="token function">deposit</span><span class="token punctuation">(</span><span class="token string">"1234567890"</span><span class="token punctuation">,</span> <span class="token number">500.0</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    
    <span class="token comment">// 验证结果</span>
    <span class="token class-name">Assert</span><span class="token punctuation">.</span><span class="token function">assertEquals</span><span class="token punctuation">(</span><span class="token number">1500.0</span><span class="token punctuation">,</span> account<span class="token punctuation">.</span><span class="token function">getBalance</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token number">0.01</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    
    <span class="token comment">// 验证模拟对象的方法是否被调用</span>
    <span class="token class-name">Mockito</span><span class="token punctuation">.</span><span class="token function">verify</span><span class="token punctuation">(</span>accountRepositoryMock<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">save</span><span class="token punctuation">(</span>account<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token class-name">Mockito</span><span class="token punctuation">.</span><span class="token function">verify</span><span class="token punctuation">(</span>notificationServiceMock<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">sendNotification</span><span class="token punctuation">(</span><span class="token string">"Deposit successful"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>

}

在这个示例中,我们使用了@RunWith(MockitoJUnitRunner.class)注解来启用Mockito框架的支持。这个注解会为我们自动初始化模拟对象和被测对象。

使用@Mock注解,我们创建了名为accountRepositoryMocknotificationServiceMock的模拟对象。使用@InjectMocks注解,我们将这些模拟对象注入到accountService对象中。

然后,我们使用Mockito.when().thenReturn()方法设置模拟对象的行为,并调用accountService.deposit()方法进行测试。最后,我们使用Assert.assertEquals()方法验证结果,并使用Mockito.verify()方法验证模拟对象的方法是否被调用。

通过这个示例,我们展示了如何使用Mockito和注解的方式对带有依赖注入的Spring组件进行测试。Mockito和注解的结合可以方便地创建和注入模拟对象,使测试更加简洁和可读。

以上就是一些Java Mockito的简单使用方法啦~ 如有问题,欢迎来交流~

Reference

原文链接:https://www.jianshu.com/p/1127afe26839

标签:account,对象,Mockito,注解,方法,模拟
From: https://www.cnblogs.com/sunny3158/p/17883646.html

相关文章

  • 可调用对象包装器和绑定器
    文章参考:爱编程的大丙(subingwen.cn)1.可调用对象一组执行任务的语句都可以视作一个函数、一个可调用对象。C++中提供了可调用对象的概念,其应用相当广泛,例如在处理一些回调函数、触发函数时就会用到。可调用对象有如下几种类型:函数指针:intadd(inta,intb){ret......
  • 59AcWing 840. 模拟散列表
    点击查看代码#include<iostream>#include<cstring>usingnamespacestd;constintN=200003,null=0x3f3f3f3f;inth[N];intfind(intx){intk=(x%N+N)%N;//索引while(h[k]!=null&&h[k]!=x){k++;if(k==N)k=0;//重新搜索......
  • 低气压试验箱:低压环境模拟的得力助手
    低气压试验箱是一种用于测试产品在低气压环境下的性能和可靠性的重要设备。随着科技的发展,许多产品需要在不同的环境和气候条件下运行,因此低气压试验箱成为了质量保证和产品研发过程中不可或缺的一部分。上海和晟HS系列低气压试验箱低气压试验箱的核心部分是它的密封舱,通常被设计......
  • 前端歌谣的刷题之路-第一百一十五题-根据包名 在指定空间中创建对象
     前言我是歌谣我有个兄弟巅峰的时候排名c站总榜19叫前端小歌谣曾经我花了三年的时间创作了他现在我要用五年的时间超越他今天又是接近兄弟的一天人生难免坎坷大不了从头再来歌谣的意志是永恒的放弃很容易但是坚持一定很酷本题目源自于牛客网微信公众号前端小歌谣题目......
  • 【UVA 101】The Blocks Problem 题解(模拟+向量)
    计算机科学的许多领域使用简单、抽象的领域进行分析和实证研究。例如,早期的人工智能规划和机器人研究(STRIPS)使用了一个区块世界,其中机器人arm执行涉及块操作的任务。在这个问题中,您将在某些规则和约束下对一个简单的块世界进行建模。相当地与确定如何达到指定状态相比,您将“编程......
  • P5048 [Ynoi2019 模拟赛] Yuno loves sqrt technology III
    题意给定序列\(s\),每次询问\(l,r\)的区间众数的出现次数。强制在线。空间:\(62.5MB\)。Sol蒲公英卡常卡空间版。考虑优化那个\(n\timesm\)的数组。我们要求\(l,r\)之中某个数的个数。乍一看不好弄,仔细想想就会发现,如果我们知道当前的最优答案。在长常数时间内就......
  • 软件需求与分析课堂测试之九-面向对象设计与分析
    软件需求与分析课堂测试之九-面向对象设计与分析 阅读下列图和文字材料,回答问题1至问题3。某物品拍卖网站为参与者提供物品拍卖平台,组织拍卖过程,提供在线或线下交易服务。网站的主要功能描述如下:(1)拍卖参与者分为个人参与者和团体参与者两种,不同的团体也可以组成新的团体参与......
  • 软件需求与分析课堂测试之九-面向对象设计与分析
    软件需求与分析课堂测试之九-面向对象设计与分析           阅读下列图和文字材料,回答问题1至问题3。某物品拍卖网站为参与者提供物品拍卖平台,组织拍卖过程,提供在线或线下交易服务。网站的主要功能描述如下:(1)拍卖参与者分为个人参与者和团体参与者两种,不同......
  • R语言SIR模型网络结构扩散过程模拟SIR模型(Susceptible Infected Recovered )代码实例|
    全文链接:http://tecdat.cn/?p=14593最近我们被客户要求撰写关于SIR模型的研究报告,包括一些图形和统计输出。与普通的扩散研究不同,网络扩散开始考虑网络结构对于扩散过程的影响。这里介绍一个使用R模拟网络扩散的例子基本的算法非常简单:生成一个网络:g(V,E)。随机选择一个或几......
  • 【愚公系列】2023年12月 面向对象设计原则(三)-里氏替换原则(Liskov Substitution Pri
    ......