pbootcms网站模板|日韩1区2区|织梦模板||网站源码|日韩1区2区|jquery建站特效-html5模板网

如何使用 mockito 或 powermock 模擬局部變量

How to mock local variables using mockito or powermock(如何使用 mockito 或 powermock 模擬局部變量)
本文介紹了如何使用 mockito 或 powermock 模擬局部變量的處理方法,對(duì)大家解決問題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧!

問題描述

我有這樣的場(chǎng)景

InputStreamReader reader = new InputStreamReader(getFileAsStream(resourceResolver, iconpath));
                BufferedReader bReader = new BufferedReader(reader);

我一直嘲諷到現(xiàn)在

getFileAsStream(resourceResolver, iconpath)

現(xiàn)在我得到了一位讀者

 BufferedReader bReader = new BufferedReader(reader);

但是當(dāng)我執(zhí)行這一行時(shí),我得到 null 并且無(wú)法繼續(xù)前進(jìn)

but when I execute this line I get null and not able to move forward

  while ((iconEntry = bReader.readLine()) != null)

請(qǐng)告訴我如何模擬這個(gè).請(qǐng)注意,我無(wú)法更改我的主要代碼,因此 Mockito 文檔中的解決方案在我的情況下無(wú)效

Please tell me how can I mock this. Please note I cannot change my main code therefore the solution present on Mockito docs is not valid in my case

測(cè)試代碼

@RunWith(PowerMockRunner.class)
@PrepareForTest({ FrameworkUtil.class, LoggerFactory.class })
public class IconPreviewServletTest {
    private IconPreviewServlet iconPreviewServlet;
    private SlingHttpServletRequest request;
    private SlingHttpServletResponse response;
    private Bundle bundle;
    private BundleContext bundleContext;
    private ServiceReference factoryRef;
    private CommonService resolverFactory;
    private PrintWriter out;
    private ResourceResolver resourceResolver;
    private Resource resource;
    private Node node;
    private Node jcrContent;
    private javax.jcr.Property property;
    private Binary binary;
    private InputStream stream;
    private InputStreamReader inputReader;
    private BufferedReader reader;

    @Before
    public void setUp() throws IOException, PathNotFoundException,
            RepositoryException {
        init();
    }

    private void init() throws IOException, PathNotFoundException,
            RepositoryException {

        request = mock(SlingHttpServletRequest.class);
        response = mock(SlingHttpServletResponse.class);
        bundleContext = mock(BundleContext.class);
        factoryRef = mock(ServiceReference.class);
        resolverFactory = mock(CommonService.class);
        out = mock(PrintWriter.class);
        resourceResolver = mock(ResourceResolver.class);
        resource = mock(Resource.class);
        node = mock(Node.class);
        jcrContent = mock(Node.class);
        property = mock(Property.class);
        binary = mock(Binary.class);
        stream=IOUtils.toInputStream("some test data for my input stream");



        reader = mock(BufferedReader.class);

        inputReader=mock(InputStreamReader.class);

        bundle = mock(Bundle.class);
        mockStatic(FrameworkUtil.class);
        mockStatic(LoggerFactory.class);

        Logger log = mock(Logger.class);

        when(LoggerFactory.getLogger(IconPreviewServlet.class)).thenReturn(log);
        when(FrameworkUtil.getBundle(CommonService.class)).thenReturn(bundle);
        when(bundle.getBundleContext()).thenReturn(bundleContext);
        when(bundleContext.getServiceReference(CommonService.class.getName()))
                .thenReturn(factoryRef);
        when(bundleContext.getService(factoryRef)).thenReturn(resolverFactory);
        when(request.getParameter("category")).thenReturn("category");
        when(request.getParameter("query")).thenReturn("query");
        when(response.getWriter()).thenReturn(out);
        when(request.getResourceResolver()).thenReturn(resourceResolver);
        when(
                resourceResolver
                        .getResource("/etc/designs/resmed/icons/category/icons.txt"))
                .thenReturn(resource);
        when(resource.adaptTo(Node.class)).thenReturn(node);
        when(node.getNode("jcr:content")).thenReturn(jcrContent);
        when(jcrContent.getProperty("jcr:data")).thenReturn(property);
        when(property.getBinary()).thenReturn(binary);
        when(binary.getStream()).thenReturn(stream);

    }

推薦答案

要做到這一點(diǎn),需要使用 Powermockito 來(lái)攔截構(gòu)造函數(shù)調(diào)用(new InputStreamReader(...), new BufferedReader(...))所以你的模擬得到回報(bào).下面是一個(gè)例子.在您的情況下,只需攔截新的 BufferedReader 調(diào)用就足夠了.

To make this work, you need to use Powermockito to intercept the constructor calls (new InputStreamReader(...), new BufferedReader(...)) so that your mocks get returned. An example is below. In your case, just intercepting the new BufferedReader call may be enough.

假設(shè)以下是您要測(cè)試的代碼:

Assume the following is the code you want to test:

package test;

import java.io.*;

public class SUT {

    public String doSomething() throws IOException {
        InputStreamReader reader =
                new InputStreamReader(getFileAsStream(null, null));
        BufferedReader bReader =
                new BufferedReader(reader);

        return bReader.readLine();
    }

    private InputStream getFileAsStream(Object resourceResolver, Object iconPath)
            throws FileNotFoundException {
        return new ByteArrayInputStream("".getBytes());
    }
}

以下測(cè)試代碼是如何攔截構(gòu)造函數(shù)調(diào)用的示例:

The following test code is an example of how to intercept the constructor calls:

package test;

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 java.io.BufferedReader;
import java.io.InputStreamReader;

import static org.junit.Assert.assertEquals;
import static org.powermock.api.mockito.PowerMockito.doReturn;
import static org.powermock.api.mockito.PowerMockito.mock;

@RunWith(PowerMockRunner.class)
@PrepareForTest({ SUT.class })
public class SUTTest {

    @Test
    public void doSomethingReturnsValueFromBufferedReader() throws Exception {
        // Arrange
        SUT sut = new SUT();
        InputStreamReader inputStreamReaderMock = mock(InputStreamReader.class);
        BufferedReader bufferedReaderMock = mock(BufferedReader.class);

        // Set your mocks up to be returned when the new ...Reader calls 
        // are executed in sut.doSomething()
        PowerMockito.whenNew(InputStreamReader.class).
                     withAnyArguments().thenReturn(inputStreamReaderMock);
        PowerMockito.whenNew(BufferedReader.class).
                     withArguments(inputStreamReaderMock).
                     thenReturn(bufferedReaderMock);

        // Set the value you want bReader.readLine() to return 
        // when sut.doSomething() executes
        final String bufferedReaderReturnValue = "myValue";
        doReturn(bufferedReaderReturnValue).when(bufferedReaderMock).readLine();

        // Act
        String result = sut.doSomething();

        // Assert
        assertEquals(bufferedReaderReturnValue, result);
    }
}

希望這能幫助您解決眼前的問題.但是,在我看來(lái),您正在創(chuàng)建的將是一個(gè)非常緩慢、令人困惑和脆弱的測(cè)試.現(xiàn)在,您的嘲笑太多了,以至于很難確定您實(shí)際上要測(cè)試什么.

This hopefully helps you in your immediate problem. However, it seems to me that what you're creating will be a very slow, confusing and brittle test. Right now, you're mocking so much that it makes very hard to determine what you're actually trying to test.

大量的模擬可能表明您正在測(cè)試的代碼的設(shè)計(jì)需要一些工作來(lái)提高可測(cè)試性.如果你不能接觸代碼,那么你就不能——但試著讓你的測(cè)試更具可讀性和直觀性(當(dāng)這個(gè)方法被調(diào)用時(shí),這件事應(yīng)該發(fā)生,因?yàn)?.....").

The high amount of mocking probably indicates that the design of the code you're testing would need some work to improve testability. If you can't touch the code, then you can't - but try to make your test more readable and intuitive ("When this method is invoked, this thing should happen, because...").

這篇關(guān)于如何使用 mockito 或 powermock 模擬局部變量的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!

【網(wǎng)站聲明】本站部分內(nèi)容來(lái)源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請(qǐng)聯(lián)系我們刪除處理,感謝您的支持!

相關(guān)文檔推薦

How to mock super reference (on super class)?(如何模擬超級(jí)參考(在超級(jí)類上)?)
Java mock database connection(Java 模擬數(shù)據(jù)庫(kù)連接)
Mockito ClassCastException - A mock cannot be cast(Mockito ClassCastException - 無(wú)法投射模擬)
Set value to mocked object but get null(將值設(shè)置為模擬對(duì)象但獲取 null)
How to mock DriverManager.getConnection(...)?(如何模擬 DriverManager.getConnection(...)?)
Mockito; verify method was called with list, ignore order of elements in list(模擬;使用列表調(diào)用驗(yàn)證方法,忽略列表中元素的順序)
主站蜘蛛池模板: 空冷器|空气冷却器|空水冷却器-无锡赛迪森机械有限公司[官网] | 泰安塞纳春天装饰公司【网站】 | 仓储笼_仓储货架_南京货架_仓储货架厂家_南京货架价格低-南京一品仓储设备制造公司 | 泥浆在线密度计厂家-防爆数字压力表-膜盒-远传压力表厂家-江苏大亚自控设备有限公司 | 合肥汽车充电桩_安徽充电桩_电动交流充电桩厂家_安徽科帝新能源科技有限公司 | 匀胶机旋涂仪-声扫显微镜-工业水浸超声-安赛斯(北京)科技有限公司 | 诗词大全-古诗名句 - 古诗词赏析| 劳动法网-专业的劳动法和劳动争议仲裁服务网 | 警用|治安|保安|不锈钢岗亭-售货亭价格-垃圾分类亭-移动厕所厂家-苏州灿宇建材 | 中央空调温控器_风机盘管温控器_智能_液晶_三速开关面板-中央空调温控器厂家 | 冷却塔减速机器_冷却塔皮带箱维修厂家_凉水塔风机电机更换-广东康明冷却塔厂家 | 上海单片机培训|重庆曙海培训分支机构—CortexM3+uC/OS培训班,北京linux培训,Windows驱动开发培训|上海IC版图设计,西安linux培训,北京汽车电子EMC培训,ARM培训,MTK培训,Android培训 | 耐高温硅酸铝板-硅酸铝棉保温施工|亿欧建设工程 | AGV无人叉车_激光叉车AGV_仓储AGV小车_AGV无人搬运车-南昌IKV机器人有限公司[官网] | 氢氧化钙设备_厂家-淄博工贸有限公司 | 全自动定氮仪-半自动凯氏定氮仪厂家-祎鸿仪器 | 杭州门窗厂家_阳光房_包阳台安装电话-杭州窗猫铝合金门窗 | 丙烷/液氧/液氮气化器,丙烷/液氧/液氮汽化器-无锡舍勒能源科技有限公司 | 【365公司转让网】公司求购|转让|资质买卖_股权转让交易平台 | BAUER减速机|ROSSI-MERSEN熔断器-APTECH调压阀-上海爱泽工业设备有限公司 | UV-1800紫外光度计-紫外可见光度计厂家-翱艺仪器(上海)有限公司 | 并离网逆变器_高频UPS电源定制_户用储能光伏逆变器厂家-深圳市索克新能源 | 石家庄装修设计_室内家装设计_别墅装饰装修公司-石家庄金舍装饰官网 | 合肥升降机-合肥升降货梯-安徽升降平台「厂家直销」-安徽鼎升自动化科技有限公司 | 蓝牙音频分析仪-多功能-四通道-八通道音频分析仪-东莞市奥普新音频技术有限公司 | 金环宇|金环宇电线|金环宇电缆|金环宇电线电缆|深圳市金环宇电线电缆有限公司|金环宇电缆集团 | 罗氏牛血清白蛋白,罗氏己糖激酶-上海嵘崴达实业有限公司 | 脉冲布袋除尘器_除尘布袋-泊头市净化除尘设备生产厂家 | 全国冰箱|空调|洗衣机|热水器|燃气灶维修服务平台-百修家电 | 暖气片十大品牌厂家_铜铝复合暖气片厂家_暖气片什么牌子好_欣鑫达散热器 | 机械加工_绞车配件_立式离心机_减速机-洛阳三永机械厂 | 河南正规膏药生产厂家-膏药贴牌-膏药代加工-修康药业集团官网 | 高柔性拖链电缆-聚氨酯卷筒电缆-柔性屏蔽电缆厂家-玖泰电缆 | 风信子发稿-专注为企业提供全球新闻稿发布服务 | 流量卡中心-流量卡套餐查询系统_移动电信联通流量卡套餐大全 | 铝合金脚手架厂家-专注高空作业平台-深圳腾达安全科技 | 滚塑PE壳体-PE塑料浮球-警示PE浮筒-宁波君益塑业有限公司 | 防水套管厂家_刚性防水套管_柔性防水套管_不锈钢防水套管-郑州中泰管道 | 网站建设-网站制作-网站设计-网站开发定制公司-网站SEO优化推广-咏熠软件 | 深圳侦探联系方式_深圳小三调查取证公司_深圳小三分离机构 | 数年网路-免费在线工具您的在线工具箱-shuyear.com |