文档: http://site.mockito.org/mockito/docs/current/org/mockito/Mockito.html
1、测试 void 方法
@Autowired private JdbcTemplate jdbcTemplate; public static final String DELETE_INSTANCE_RELY_BY_TASK = " DELETE FROM tb_instance_rely_rel " + "WHERE task_id=? AND instance_id IN ( SELECT c.instance_id FROM " + "(SELECT task_id FROM tb_task WHERE task_id=? )a JOIN tb_data_version b " + " ON a.task_id = " + " b.task_id JOIN tb_instance c ON b.version_id = c.version_id WHERE c.state=? )"; @Override public void deleteInitializedInstanceRelyByTask(long taskId, long upTaskId) { final Object[] args = { upTaskId, taskId, InstanceState.INITIALIZED.getValue() }; LOGGER.debug(Tools.getSqlArgsString(DELETE_INSTANCE_RELY_BY_TASK, args)); jdbcTemplate.update(DELETE_INSTANCE_RELY_BY_TASK, args); }
测试代码片段:
private JdbcTemplate jdbcTemplate; private InstanceRelyRelDaoImpl impl; private long taskId = 100L; private long upTaskId = 101L; @Before public void before() { jdbcTemplate = mock(JdbcTemplate.class); impl = new InstanceRelyRelDaoImpl(); Whitebox.setInternalState(impl, "jdbcTemplate", jdbcTemplate); } public void testDeleteInitializedInstanceRelyByTask() { impl.deleteInitializedInstanceRelyByTask(taskId, upTaskId); Object[] args = { upTaskId, taskId, InstanceState.INITIALIZED.getValue() }; Mockito.verify(jdbcTemplate).update(InstanceRelyRelDaoImpl.DELETE_INSTANCE_RELY_BY_TASK, args); }
2、测试static 静态方法
import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.powermock.api.mockito.PowerMockito.mock; import static org.powermock.api.mockito.PowerMockito.mockStatic; import static org.powermock.api.mockito.PowerMockito.when; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.reflect.Whitebox; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.PreparedStatementCreator; import org.springframework.jdbc.support.KeyHolder; import java.util.Date; @RunWith(PowerMockRunner.class) // mock静态方法,必须有 @PrepareForTest({ Utils.class }) // mock静态方法,必须有 public class EntitySubscribeFlowDaoImplTest { private EntitySubscribeFlowDaoImpl impl; private JdbcTemplate jdbcTemplate; @Before public void before() { impl = new EntitySubscribeFlowDaoImpl(); jdbcTemplate = mock(JdbcTemplate.class); Whitebox.setInternalState(impl, "jdbcTemplate", jdbcTemplate); } /** * Test method */ @Test public void testAddEntitySubscribeFlow() { try { impl.addEntitySubscribeFlow(null); fail(); } catch (Exception e) { assertTrue(true); } try { EntitySubscribeFlow flow = new EntitySubscribeFlow(); KeyHolder keyHolder = mock(KeyHolder.class); mockStatic(Utils.class); // mock静态方法,必须有 when(Utils.createKeyHolder()).thenReturn(keyHolder); // mock静态方法,必须有 when(keyHolder.getKey()).thenReturn(10L); long id = impl.addEntitySubscribeFlow(flow); Mockito.verify(jdbcTemplate).update(Mockito.any(PreparedStatementCreator.class), Mockito.any(KeyHolder.class)); System.err.println("================= " + id); } catch (Exception e) { e.printStackTrace(); fail(); } } }
3、mock 掉方法中的 private 私有方法
参考地址: http://automationrhapsody.com/mock-private-method-call-powermock/
public class PowerMockDemo { public Point callPrivateMethod() { return privateMethod(new Point(1, 1)); } private Point privateMethod(Point point) { return new Point(point.getX() + 1, point.getY() + 1); } }
import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.Matchers.anyObject; import static org.mockito.Mockito.mock; @RunWith(PowerMockRunner.class) @PrepareForTest(PowerMockDemo.class) public class PowerMockDemoTest { private PowerMockDemo powerMockDemoSpy; @Before public void setUp() { powerMockDemoSpy = PowerMockito.spy(new PowerMockDemo()); } @Test public void testMockPrivateMethod() throws Exception { Point mockPoint = mock(Point.class); PowerMockito.doReturn(mockPoint) .when(powerMockDemoSpy, "privateMethod", anyObject()); Point actualMockPoint = powerMockDemoSpy.callPrivateMethod(); assertThat(actualMockPoint, is(mockPoint)); } }
或者
@Test public void testCompose() { Train train = new Train(); Train trainSpy = Mockito.spy(train); //notice different Mockito syntax for spy Mockito.doReturn(TESTING_WAGON_COUNT).when(trainSpy).getWagonsCount(); Mockito.doNothing().when(trainSpy).addWagon(0); // invoke testing method int actualWagonCount = trainSpy.compose(); Assert.assertEquals(actualWagonCount, TESTING_WAGON_COUNT); Mockito.verify(trainSpy, Mockito.times(TESTING_WAGON_COUNT)) .addWagon(0); }
网上找的的一些其他人的例子:
参考地址: http://chenjingbo.iteye.com/blog/1696488
@Test public void testCreateMarketingDetail() throws Exception { PowerMockito.doReturn(marketingDetail).when(internalMarketingBuilder,"createMarketingDetail",marketingActivity); Assert.assertTrue(umpDetailManager.createMarketingDetail(marketingActivity).getDetailId() == detailId); } @Test(expected = ManagerException.class) public void testCreateMarketingDetail_Exception() throws Exception { PowerMockito.doThrow(new RuntimeException("test")).when(internalMarketingBuilder, "createMarketingDetail", marketingActivity); Assert.assertTrue(umpDetailManager.createMarketingDetail(marketingActivity).getDetailId() == detailId); } @Test(expected = ManagerException.class) public void testCreateMarketingDetail_Exception2() throws Exception { umpDetailManager.createMarketingDetail(null); } @Test public void testAddMarketingDetail() throws Exception { PowerMockito.doReturn(content).when(internalMarketingBuilder,"build",marketingDetail); PowerMockito.doReturn(prepareResultSupport()).when(marketingActivityTopServiceClient,"addMarketingDetail",activityId,content,sellerId); Assert.assertEquals(umpDetailManager.addMarketingDetail(activityId,marketingDetail,sellerId).getDefaultModel(),detailId); } @Test(expected = ManagerException.class) public void testAddMarketingDetail_Exception() throws Exception { PowerMockito.doReturn(content).when(internalMarketingBuilder,"build",marketingDetail); PowerMockito.doThrow(new RuntimeException("test")).when(marketingActivityTopServiceClient,"addMarketingDetail",activityId,content,sellerId); umpDetailManager.addMarketingDetail(activityId,marketingDetail,sellerId); } @Test public void testDeleteMarketingDetail() throws Exception { PowerMockito.doReturn(prepareResultSupport2()).when(marketingActivityTopServiceClient,"deleteMarketingDetail",detailId,sellerId); Assert.assertFalse(umpDetailManager.deleteMarketingDetail(detailId,sellerId).isSuccess()); } @Test(expected = ManagerException.class) public void testDeleteMarketingDetail_Exception() throws Exception { PowerMockito.doThrow(new RuntimeException("test")).when(marketingActivityTopServiceClient,"deleteMarketingDetail",detailId,sellerId); Assert.assertFalse(umpDetailManager.deleteMarketingDetail(detailId,sellerId).isSuccess()); } @Test public void testUpdateMarketingActivityDetail() throws Exception { PowerMockito.doReturn(content).when(internalMarketingBuilder,"build",marketingDetail); PowerMockito.doReturn(prepareResultSupport2()).when(marketingActivityTopServiceClient,"updateMarketingDetail",detailId,content,sellerId); Assert.assertFalse(umpDetailManager.updateMarketingActivityDetail(detailId,marketingDetail,sellerId).isSuccess()); } @Test(expected = ManagerException.class) public void testUpdateMarketingActivityDetail_Exception() throws Exception { PowerMockito.doReturn(content).when(internalMarketingBuilder,"build",marketingDetail); PowerMockito.doThrow(new RuntimeException("test")).when(marketingActivityTopServiceClient,"updateMarketingDetail",detailId,content,sellerId); Assert.assertFalse(umpDetailManager.updateMarketingActivityDetail(detailId,marketingDetail,sellerId).isSuccess()); }
相关推荐
ta_lib-0.5.1-cp312-cp312-win32.whl
课程设计 在线实时的斗兽棋游戏,时间赶,粗暴的使用jQuery + websoket 实现实时H5对战游戏 + java.zip课程设计
ta_lib-0.5.1-cp310-cp310-win_amd64.whl
基于springboot+vue物流系统源码数据库文档.zip
GEE训练教程——Landsat5、8和Sentinel-2、DEM和各2哦想指数下载
知识图谱
333498005787635解决keil下载失败的文件.zip
【微信机器人原理与实现】 微信机器人是通过模拟微信客户端的行为,自动处理消息、发送消息的程序。在Python中实现微信机器人的主要库是WeChatBot,它提供了丰富的接口,允许开发者方便地进行微信消息的接收与发送。这个项目标题中的"基于python实现的微信机器人源码"指的是使用Python编程语言编写的微信机器人程序。 1. **Python基础**:Python是一种高级编程语言,以其简洁的语法和强大的功能深受开发者喜爱。在实现微信机器人时,你需要熟悉Python的基本语法、数据类型、函数、类以及异常处理等概念。 2. **微信API与WeChatBot库**:微信为开发者提供了微信公共平台和微信开放平台,可以获取到必要的API来实现机器人功能。WeChatBot库是Python中一个用于微信开发的第三方库,它封装了微信的API,简化了消息处理的流程。使用WeChatBot,开发者可以快速搭建起一个微信机器人。 3. **微信OAuth2.0授权**:为了能够接入微信,首先需要通过OAuth2.0协议获取用户的授权。用户授权后,机器人可以获取到微信用户的身份信息,从而进行
基于springboot实验室研究生信息管理系统源码数据库文档.zip
张力控制,色标跟踪,多轴同步,电子凸轮,横切等工艺控制案例。
在Python编程环境中,处理Microsoft Word文档是一项常见的任务。Python提供了几个库来实现这一目标,如`python-docx`,它可以让我们创建、修改和操作.docx文件。本教程将重点介绍如何利用Python进行Word文档的合并、格式转换以及转换为PDF。 1. **合并Word文档(merge4docx)** 合并多个Word文档是一项实用的功能,特别是在处理大量报告或文档集合时。在Python中,可以使用`python-docx`库实现。我们需要导入`docx`模块,然后读取每个文档并将其内容插入到主文档中。以下是一个基本示例: ```python from docx import Document def merge4docx(file_list, output_file): main_doc = Document() for file in file_list: doc = Document(file) for paragraph in doc.paragraphs: main_doc.add_paragraph(paragraph.text) m
基于springboot+Javaweb的二手图书交易系统源码数据库文档.zip
基于springboot餐品美食论坛源码数据库文档.zip
基于springboot亚运会志愿者管理系统源码数据库文档.zip
使用WPF的数据样式绑定,切换对象数据值来完成控件动态切换背景渐变动画效果。 使用动画样式渲染比线程修改性能消耗更低更稳定
基于SpringBoot的企业客源关系管理系统源码数据库文档.zip
基于springboot+vue的桂林旅游网站系统源码数据库文档.zip
基于springboot嗨玩旅游网站源码数据库文档.zip
基于springboot的流浪动物管理系统源码数据库文档.zip
基于springboot课件通中小学教学课件共享平台源码数据库文档.zip