`
kanpiaoxue
  • 浏览: 1781685 次
  • 性别: Icon_minigender_1
  • 来自: 北京
文章分类
社区版块
存档分类
最新评论

PowerMockit常用

 
阅读更多

 

文档: 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());  
    }  

 

 

 

 

 

 

 

 

 

 

 

 

 

分享到:
评论

相关推荐

    基于net的超市管理系统源代码(完整前后端+sqlserver+说明文档+LW).zip

    功能说明: 环境说明: 开发软件:VS 2017 (版本2017以上即可,不能低于2017) 数据库:SqlServer2008r2(数据库版本无限制,都可以导入) 开发模式:mvc。。。

    LABVIEW程序实例-公式节点.zip

    labview程序代码参考学习使用,希望对你有所帮助。

    大米商城开源版damishop(适合外贸)

    大米外贸商城系统 简称damishop 完全开源版,只需做一种语言一键开启全球133中语言自动翻译功能,价格实现自动汇率转换,集成微信支付宝 paypal以及国外主流支付方式,自带文章博客系统。 软件架构 基于MVC+语言包模式,增加控制台,API导入产品方便对接其他系统(带json示例数据)。 使用要求 PHP7.4+ MYSQL5.6+ REDIS(可选) 安装方法 composer install 打开安装向导安装 http://您的域名/install 特色 1、缓存层增加时间与批量like删除 2、API产品导入方便对接其他系统 3、增加控制台命令行,命令行生成语言翻译包 4、后台一键开启自动翻译模式,支持全球133中语言,由于google代理翻译需要收费,这个功能需要付费。 5、可选购物车与ajax修改购物车产品 6、一键结算checkout 7、增加网站前台自定义路由 方便seo 更新日志 v3.9.7 集成鱼码支付接口,方便个人站长即使收款到账使用 v3.9.3 更新内容 1:增加ueditor与旧编辑器切换 2:增加可视化布局插

    LABVIEW程序实例-通过全局变量接收数据.zip

    labview程序代码参考学习使用,希望对你有所帮助。

    LABVIEW程序实例-日历控件.zip

    labview程序代码参考学习使用,希望对你有所帮助。

    毕设和企业适用springboot人工智能客服系统类及旅游规划平台源码+论文+视频.zip

    毕设和企业适用springboot人工智能客服系统类及旅游规划平台源码+论文+视频

Global site tag (gtag.js) - Google Analytics