Using mockito in java

本文介绍了如何利用Mockito工具创建模拟对象,解决单元测试中依赖于其他对象的问题,并通过具体示例展示了如何验证模拟对象的调用和执行正确的行为。
If you’ve spent any time writing unit tests then you’ll know that it’s not always straight-forward. Certain things are inherently hard to test. In this post I’ll show you the basic principles of creating mock objects with a little help from the Mockito mocking tool.


One common problem faced when unit testing is how to test one object when it is dependant on another object. You could create instances of both the object under test and the dependent object and test them both together, however testing aggregated objects is not what unit testing is about – unit tests should test individual objects for their correct behaviour, not aggregations of objects! Moreover, this approach just won’t work if the dependent object hasn’t even been implemented yet.


A common technique for handling dependencies in unit tests is to provide a surrogate, or “mock” object, for the dependent object instead of a real one. The mock object will implement a simplified version of the real objects methods that return predictable results and can be used for testing purposes.


The drawback of this approach is that in a complex application, you could find yourself creating a lot of mock objects. This is where frameworks like Mockito can save you a lot of time and effort.
A Test Scenario


To demonstrate what you can do with Mockito, we’ll examine how we might test an Account object that is dependant on a data access object (AccountDAO).  The account object can calculate the charges applicable in the current month by using the DAO to count the number of days overdrawn and then performing a simple calculation on the value obtained from that call. The method names on the classes we’ll use are self-explanatory:


AccountAndDAO
To test this thoroughly, we should test two things:


   1. that the account obtains the number of overdrawn days by calling the correct method on the DAO,
   2. that the account calculates the correct fees based upon the value it gets back from the call.


Testing that the account calls the correct method on the DAO


Using JUnit to run the test case, we could write something like this:
01.import static org.mockito.Mockito.*;
02. 
03.public class TestAccount {
04.@Test
05.public void checkAccountCallsDaoMethods() {
06.//create the object under test
07.Account account = new Account();
08. 
09.//create a mock DAO
10.AccountDAO mockedDao = mock(AccountDAO.class); 
11. 
12.//associate the mocked DAO with the object under test
13.account.setDAO(dao);
14. 
15.//call the method under test
16.long charge = account.calculateCharges();
17. 
18.//verify that the 'countOverdrawnDaysThisMonth' was called
19.verify(mockedDao).countOverdrawnDaysThisMonth();
20.}
21.}


Taking centre stage in all this is the Mockito class which has a bunch of static methods that are used within the unit test (note the static import on line 1).


The call to the ‘mock’ method (line 10) creates a mock object that can be used in place of a real AccountDAO. The call to ‘verify’ (line 19), will throw an exception if the ‘countOverdrawnDaysThisMonth’ method was not called on the mock object.


It is worth noting here that this is a simple example which just demonstrates the basic principle of verification, it is also possible to use the verify method to check for parameter values and ranges in the method call too.
Testing that the account performs its calculations correctly


In the above example, we mocked the DAO but didn’t specify what any of the mocked methods should do. In this case, all methods will return sensible default values of: null, zero or false. More commonly we need to specify something other than these defaults when writing our tests:
01.import static org.mockito.Mockito.*;
02.import static junit.framework.Assert.*;
03.import org.junit.*;
04. 
05.public class TestAccount {
06.private Account account;
07. 
08.@Before
09.public void setup() {
10.AccountDAO mockedDao = mock(AccountDAO.class);
11. 
12.//specify that this method on the mock object should return 8
13.when(mockedDao.countOverdrawnDaysThisMonth()).thenReturn(8);
14. 
15.account = new Account();
16.account.setDAO(dao);
17.}
18. 
19.@Test
20.public void checkChargesWhenOverdrawn() {
21.//call the method under test
22.long charge = account.calculateCharges();
23. 
24.//assert that the charge was £2 per day overdrawn
25.assertEquals(charge, 16);
26.}
27.}


The statement on line 18 specifies that whenever the ‘countOverdrawnDaysThisMonth’ is called it should return a value of 8; overriding the default of zero.


Given that the correct charge is two pounds (or dollars) per day overdrawn, then the assertion on line 25 will pass if the account performed the correct calculation (8 x 2 = 16 right).
Comments


There’s loads more to Mockito than we’ve looked at here. It’s a neat testing tool that works great with JUnit or TestNG. I’ve found that it’s small enough to learn quickly and capable enough to be really useful. Give it a go and write a comment below to let me know what you think of it
【路径规划】(螺旋)基于A星全覆盖路径规划研究(Matlab代码实现)内容概要:本文围绕“基于A星算法的全覆盖路径规划”展开研究,重点介绍了一种结合螺旋搜索策略的A星算法在栅格地图中的路径规划实现方法,并提供了完整的Matlab代码实现。该方法旨在解决移动机器人或无人机在未知或部分已知环境中实现高效、无遗漏的区域全覆盖路径规划问题。文中详细阐述了A星算法的基本原理、启发式函数设计、开放集与关闭集管理机制,并融合螺旋遍历策略以提升初始探索效率,确保覆盖完整性。同时,文档提及该研究属于一系列路径规划技术的一部分,涵盖多种智能优化算法与其他路径规划方法的融合应用。; 适合人群:具备一定Matlab编程基础,从事机器人、自动化、智能控制及相关领域研究的研究生、科研人员及工程技术人员。; 使用场景及目标:①应用于服务机器人、农业无人机、扫地机器人等需要完成区域全覆盖任务的设备路径设计;②用于学习和理解A星算法在实际路径规划中的扩展应用,特别是如何结合特定搜索策略(如螺旋)提升算法性能;③作为科研复现与算法对比实验的基础代码参考。; 阅读建议:建议结合Matlab代码逐段理解算法实现细节,重点关注A星算法与螺旋策略的切换逻辑与条件判断,并可通过修改地图环境、障碍物分布等方式进行仿真实验,进一步掌握算法适应性与优化方向。
<think> 首先,用户的问题是:“我想查找使用JavaMockito进行单元测试时构造List<Set<Long>>类型数据的方法。请问Java Mockito单元测试中构造List<Set<Long>>类型数据的方法。” 我需要基于提供的引用内容来回答。引用是关于Mockito框架的使用的,包括如何模拟对象、验证方法调用等。 关键点: - 用户需要构造List<Set<Long>>类型的数据。 - 这是一个集合的集合:List包含Set<Long>元素。 - 在单元测试中,使用Mockito,我们通常模拟对象或创建真实对象来测试。 从引用中提取相关部分: - 引用[2]:提到了模拟有参构造函数对象Mock,使用Mockito.mockConstruction来处理对象构造。 - 引用[4]:展示了使用@Mock注解来模拟List对象。 - 引用[5]:讨论了mock对象如何记住交互,并展示了如何验证方法调用。 用户需要构造List<Set<Long>>类型的数据,而不一定是模拟它。构造数据意味着创建实际的数据结构,比如用于测试输入或预期输出。 在单元测试中,构造数据可以是: - 创建真实的对象实例。 - 使用Mockito模拟对象(如果需要模拟行为)。 对于List<Set<Long>>,我可以: 1. 手动创建实际的List和Set。 2. 使用Mockito模拟List对象(如果需要模拟其行为)。 从引用看: - 引用[4]展示了@Mock用于模拟List对象。 - 引用[5]展示了模拟List并添加元素。 但用户说“构造List<Set<Long>>类型数据”,这可能意味着创建实际的数据,而不是模拟。在测试中,如果需要测试真实逻辑,可能会创建真实对象;如果需要隔离测试,可能会模拟依赖。 参考引用: - 引用[1]:Mockito用于模拟对象以便测试。 - 引用[3]:Mockito允许在不依赖外部资源的情况下测试。 用户的具体查询是“构造List<Set<Long>>类型数据的方法”。在Java中,构造这样的数据结构很简单: - 使用ArrayList和HashSet。 - 例如:创建一个List,其中每个元素是一个Set<Long>。 然后,在Mockito测试中如何使用: - 如果这个List是测试的一部分,比如作为输入参数,可以直接创建它。 - 如果它是一个依赖项需要模拟,可以使用Mockito.mock或@Mock。 从引用[4]:使用了@Mock private List mockList; 来模拟一个List。 类似地,可以模拟List<Set<Long>>,但Mockito的mock方法可以处理泛型。 在Mockito中,模拟泛型类型是可行的,例如: ```java List<Set<Long>> mockList = Mockito.mock(List.class); ``` 或者使用@Mock。 但如果用户需要构造实际数据,而不是模拟,我应该侧重于如何创建真实对象。 用户说“使用JavaMockito进行单元测试时构造”,所以可能涉及如何在测试中创建这样的数据结构。 在回答中,我应该: - 解释如何创建真实的List<Set<Long>>。 - 展示如何在Mockito测试中使用它(例如,作为测试方法的输入)。 - 如果需要模拟List<Set<Long>>,展示如何mock它。 参考引用[5]:它展示了模拟List并添加元素: ```java final List mockList = Mockito.mock(List.class); mockList.add("mock1"); ``` 类似地,对于List<Set<Long>>,我可以mock它并设置行为。 更好的方法是: - 先展示如何构造真实数据。 - 然后,如果需要mock,展示如何mock它。 回答结构: 1. 介绍在单元测试中构造数据的方法。 2. 展示代码示例。 3. 引用相关引用。 系统指令: - 使用中文回答。 - 结构清晰。 - 生成相关问题。 - 行内数学用$...$,但这里可能不需要数学。 - 独立公式用$$...$$,但不需要。 - 添加引用标识。 最后,生成相关问题。 步骤: 1. 回答用户问题。 2. 添加引用。 3. 生成相关问题。 **Constructing Real Data:** 在Java中,创建List<Set<Long>>很简单: ```java List<Set<Long>> listOfSets = new ArrayList<>(); Set<Long> set1 = new HashSet<>(); set1.add(1L); set1.add(2L); Set<Long> set2 = new HashSet<>(); set2.add(3L); listOfSets.add(set1); listOfSets.add(set2); ``` **Using in Mockito Test:** 在单元测试中,你可以将上述数据作为输入或预期输出。例如: ```java @Test public void testSomething() { List<Set<Long>> input = new ArrayList<>(); // 添加元素... // 调用被测试方法 SomeClass.someMethod(input); // 验证结果 } ``` **Mocking if Needed:** 如果需要模拟List<Set<Long>>的行为,可以使用Mockito: ```java List<Set<Long>> mockList = Mockito.mock(List.class); // 设置stub行为 when(mockList.get(0)).thenReturn(new HashSet<>(Arrays.asList(1L, 2L))); // 在测试中使用mockList ``` 从引用[5],它有when和verify的示例。 引用相关部分: - 引用[4]展示了@Mock用于List。 - 引用[5]展示了mock和verify。 添加引用标识:[^4], [^5] 生成相关问题: 1. 如何设置Mockito来模拟List的特定方法? 2. 在单元测试中如何验证List<Set<Long>>的正确性? 3. Mockito支持哪些方式来创建复杂数据结构? 确保回答真实可靠。 </think> ### Java Mockito单元测试中构造List<Set<Long>>类型数据的方法 在单元测试中构造List<Set<Long>>类型数据时,通常有两种场景:(1) 创建真实数据对象用于测试输入或预期输出;(2) 使用Mockito模拟对象以控制依赖行为。以下是具体方法,基于Java集合框架和Mockito功能实现(参考引用内容)。 #### 1. **创建真实数据对象** 如果测试需要实际数据结构(如作为方法参数或验证输出),可直接使用Java标准库创建List<Set<Long>>实例。示例代码如下: ```java import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class RealDataTest { @Test public void testWithRealData() { // 创建 Set<Long> 实例 Set<Long> set1 = new HashSet<>(); set1.add(1L); set1.add(2L); Set<Long> set2 = new HashSet<>(); set2.add(3L); set2.add(4L); // 创建 List<Set<Long>> 实例并添加元素 List<Set<Long>> listOfSets = new ArrayList<>(); listOfSets.add(set1); listOfSets.add(set2); // 在测试中使用数据:例如调用被测方法 SomeService service = new SomeService(); int result = service.processList(listOfSets); assertEquals(2, result); // 验证预期结果 } } ``` - **优点**:简单直接,适用于集成测试或验证真实逻辑。 - **注意事项**:确保数据初始化完整,避免空指针异常。 #### 2. **使用Mockito模拟对象** 如果List<Set<Long>>是外部依赖(如DAO或服务),需隔离测试,可通过Mockito模拟其行为: - **基本模拟**:使用Mockito.mock()创建模拟对象并设置桩行为。 ```java import org.junit.Test; import org.mockito.Mockito; import java.util.*; public class MockitoTest { @Test public void testMockList() { // 模拟 List<Set<Long>> 对象 List<Set<Long>> mockList = Mockito.mock(List.class); // 设置桩行为:例如当调用 get(0) 时返回特定 Set<Long> Set<Long> stubSet = new HashSet<>(Arrays.asList(10L, 20L)); Mockito.when(mockList.get(0)).thenReturn(stubSet); // 设置桩行为:模拟 size() 方法返回值 Mockito.when(mockList.size()).thenReturn(2); // 在测试中使用模拟对象 TestedClass testedObj = new TestedClass(); int count = testedObj.countElements(mockList); assertEquals(2, count); // 验证逻辑 // 验证方法调用(参考引用[5]) Mockito.verify(mockList).size(); // 验证 size() 被调用至少1次 } } ``` - **关键点**:Mockito自动处理泛型类型擦除,直接用List.class即可模拟List<Set<Long>>。 - **注解方式模拟**:使用@Mock注解简化代码(需搭配@RunWith)。 ```java import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import java.util.*; @RunWith(MockitoJUnitRunner.class) // 必须添加Runner(参考引用[4]) public class AnnotationTest { @Mock private List<Set<Long>> mockList; // 直接声明泛型类型 @Test public void testAnnotationMock() { // 设置桩行为 Set<Long> stubSet = new HashSet<>(Arrays.asList(5L, 6L)); Mockito.when(mockList.get(0)).thenReturn(stubSet); // 测试逻辑 assertTrue(mockList.get(0).contains(5L)); // 验证交互(参考引用[5]) Mockito.verify(mockList).get(0); } } ``` #### 3. **混合方法:模拟嵌套行为** 若Set<Long>元素也需要模拟(例如控制contains()等方法),可嵌套模拟: ```java @Test public void testNestedMock() { List<Set<Long>> mockList = Mockito.mock(List.class); Set<Long> mockSet = Mockito.mock(Set.class); // 设置嵌套桩行为 Mockito.when(mockSet.contains(Mockito.anyLong())).thenReturn(true); Mockito.when(mockList.get(0)).thenReturn(mockSet); // 验证:例如检查contains逻辑 assertTrue(mockList.get(0).contains(100L)); Mockito.verify(mockSet).contains(100L); } ``` #### 最佳实践建议 - **优先使用真实数据**:当测试逻辑不依赖外部行为时,创建真实对象更可靠(如使用ArrayList和HashSet)。 - **模拟隔离依赖**:当List<Set<Long>>涉及数据库或网络时,使用Mockito避免外部影响(参考引用[1])。 - **验证交互**:通过Mockito.verify()确保方法调用符合预期(参考引用[5])。 - **参数处理**:注意方法参数类型匹配,避免因类型错误导致桩设置失败(参考引用[4])。 通过以上方法,您可灵活构造List<Set<Long>>数据类型,适用于各类单元测试场景[^4][^5]。 --- ### 相关问题 1. **如何在Mockito中添加多个桩行为以模拟复杂数据结构?** 2. **Mockito验证方法调用时如何指定调用次数或超时限制?** 3. **在单元测试中如何处理List<Set<Long>>的边界情况(如空列表或null元素)?**
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值