原版代码:

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/*
    7.4 替换一个HTTP连接

    学习到如何为没有Java接口的类(即HttpURLConnection类)编写mock。
 */

public class WebClient {
    public String getContent (URL url){
        StringBuffer content = new StringBuffer();
        try{
            HttpURLConnection connection = (HttpURLConnection)url.openConnection();
            connection.setDoInput(true);
            InputStream in = connection.getInputStream();
            byte[] buffer = new byte[2048];
            int count;
            while (-1 != (count = in.read(buffer))) {
                content.append(new String(buffer,0,count));
            }
        } catch (IOException e) {
            return null;
        }
        return content.toString();
    }
}

采用方法工厂重构:

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/*
    第一次重构
 */

public class WebClient1 {
    public String getContent (URL url){
        StringBuffer content = new StringBuffer();
        try{
            HttpURLConnection connection = createHttpURLConnection(url);
            connection.setDoInput(true);
            InputStream in = connection.getInputStream();
            byte[] buffer = new byte[2048];
            int count;
            while (-1 != (count = in.read(buffer))) {
                content.append(new String(buffer,0,count));
            }
        } catch (IOException e) {
            return null;
        }
        return content.toString();
    }

    protected HttpURLConnection createHttpURLConnection(URL url) throws IOException {
        return (HttpURLConnection)url.openConnection();
    }
}

对其的测试:

import org.junit.Test;

import java.net.HttpURLConnection;
import java.net.URL;

/*
public class TestWebClient1 {

    @Test
    public void testGetContentOk() throws Exception{
        MockHttpConnection mockHttpConnection = new MockHttpConnection();
        mockHttpConnection.setExpectedInputStream(new Byt
        、、、
    }

    private class TestableWebClient1 extends WebClient1{
        private HttpURLConnection connection;

        public void setHttpURLConnection(HttpURLConnection connection) {
            this.connection=connection;
        }

        public HttpURLConnection createHttpURLConnection(URL url) {
            return this.connection;
        }
    }
}
*/

采用类工厂重构:

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

interface ConnectionFactory{
    InputStream getData() throws Exception;
}

public class WebClient2 {
    public String getContent (ConnectionFactory factory){
        StringBuffer content = new StringBuffer();
        try{
            InputStream in = factory.getData();
            byte[] buffer = new byte[2048];
            int count;
            while (-1 != (count = in.read(buffer))) {
                content.append(new String(buffer,0,count));
            }
        } catch (IOException e) {
            return null;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return content.toString();
    }
}

对其的测试:

import org.junit.Test;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.Connection;

public class TestWebClient2 {

    @Test
    public void testGetContentOk(){

    }

    public class HttpURLConnectionFactory implements ConnectionFactory{
        private URL url;

        public HttpURLConnectionFactory(URL url) {
            this.url = url;
        }

        public InputStream getData() throws Exception {
            HttpURLConnection connection =
                    (HttpURLConnection)this.url.openConnection();
            return connection.getInputStream();
        }
    }
    public class MockURLConnectionFactory implements ConnectionFactory{
        private InputStream inputStream;

        public void setInputStream(InputStream inputStream) {
            this.inputStream = inputStream;
        }

        public InputStream getData() throws Exception {
            return inputStream;
        }
    }
}

当没有接口时、不可继承时,如果使用mock方案进行单元测试的更多相关文章

  1. C#构造函数在继承时必须要求与父类型构造函数入参相同怎么办?

    摘要 我们都知道,C#中,在类型继承时,由于构造子类必须先构造其父类型的内容,因此,必须子类型的构造函数中调用父类型的构造函数(无参数的不需要显式声明). 但是往往我们会出现,子类型本身的构造函数大于 ...

  2. C++使用继承时子对象的内存布局

    C++使用继承时子对象的内存布局 // */ // ]]>   C++使用继承时子对象的内存布局 Table of Contents 1 示例程序 2 对象的内存布局 1 示例程序 class ...

  3. JAVA继承时this和super关键字

    JAVA继承时this和super关键字 本文主要讨论在方法前使用this或super关键字时,编译器在什么地方查找对应的函数. 在子类中指定this关键字.首先在本类中查找,如果本类中找不到,再在父 ...

  4. JAVA中继承时方法的重载(overload)与重写/覆写(override)

    JAVA继承时方法的重载(overload)与重写/覆写(override) 重载-Override 函数的方法参数个数或类型不一致,称为方法的重载. 从含义上说,只要求参数的个数或参数的类型不一致就 ...

  5. Java继承时的初始化顺序

    Java程序在启动和运行时,需要首先完成初始化的工作.在涉及到继承.static成员变量等因素时,初始化的顺序就复杂起来.下面以一个例子说明继承时的Java初始化顺序. 例子: class Insec ...

  6. C++在单继承、多继承、虚继承时,构造函数、复制构造函数、赋值操作符、析构函数的执行顺序和执行内容

    一.本文目的与说明 1. 本文目的:理清在各种继承时,构造函数.复制构造函数.赋值操作符.析构函数的执行顺序和执行内容. 2. 说明:虽然复制构造函数属于构造函数的一种,有共同的地方,但是也具有一定的 ...

  7. c/c++ 继承与多态 继承时如何改变个别成员的访问属性

    问题1:若类B以private的方式继承类A,但还想让类A的某些个别成员,保持public或者protected的访问属性,这时应该怎么办? 使用using,去改变访问属性. #include < ...

  8. C++类有继承时,析构函数必须为虚函数

    C++类有继承时,析构函数必须为虚函数.如果不是虚函数,则使用时可能存在内在泄漏的问题. 假设我们有这样一种继承关系: 如果我们以这种方式创建对象: SubClass* pObj = new SubC ...

  9. Lombok 继承时应注意的点

    lombok项目的产生就是为了省去我们手动创建getter和setter等基本方法的麻烦,它能够在我们编译源码的时候自动帮我们生成getter和setter等方法.即它最终能够达到的效果是:在源码中没 ...

随机推荐

  1. imp dll时遇见的非常恶心的问题

    我需要导入dll库中这样一个函数VM661JTCPDLL_API int admin_login(sel_admin_ret* sel_admins, int num, char* admin_nam ...

  2. WPF 调用API修改窗体风格实现真正的无边框窗体

    原文:WPF 调用API修改窗体风格实现真正的无边框窗体 WPF中设置无边框窗体似乎是要将WindowStyle设置为None,AllowTransparency=true,这样才能达到WinForm ...

  3. CoolFormat(Qt Creator也可管理VC的Project)

    http://download.csdn.net/download/akof1314/8457593 https://github.com/akof1314/CoolFormat http://dow ...

  4. QT5.6,5.7,5.8的新特征以及展望(Qt5.7首次正式支持Qt3D,以前都是预览版)

    https://wiki.qt.io/New_Features_in_Qt_5.6 (跨平台High-DPI,改进WebEngine到45,支持WIN 10,Canvas3D,3D) https:// ...

  5. Qt项目里的源代码默认都是Unicode,原因大概是因为qmake.conf里的定义

    MAKEFILE_GENERATOR = MINGWQMAKE_PLATFORM = win32 mingwCONFIG += debug_and_release debug_and_release_ ...

  6. “多团队大规模”开发模式 - 基于SAP HANA平台的多团队产品研发

    应用SAP HANA “官方”开发模式的伙伴们在转到“多团队大规模”开发模式时会遇到各式各样的心理不适应的状况,各种纠结.比如GIT Repository和HANA Repository冲突什么的. ...

  7. 客服端JavaScript线程模型

    JavaScript语言核心并不包含任何线程机制,并且客服端JavaScript传统上没有定义任何线程机制.HTML5定义了一种作为后台线程的“WebWorker",但是客服端JavaScr ...

  8. python字典的内建函数

    In [70]: test=dict(x=1,y=2,z=3) In [71]: test Out[71]: {'x': 1, 'y': 2, 'z': 3} In [72]: a=['a','b', ...

  9. TCP使用注意事项总结

    目录 发送或者接受数据过程中对端可能发生的情况汇总 本端TCP发送数据时对端进程已经崩溃 本端TCP发送数据时对端主机已经崩溃 本端TCP发送数据时对端主机已经关机 某个连接长时间没有数据流动 TCP ...

  10. 死磕 java同步系列之CyclicBarrier源码解析——有图有真相

    问题 (1)CyclicBarrier是什么? (2)CyclicBarrier具有什么特性? (3)CyclicBarrier与CountDownLatch的对比? 简介 CyclicBarrier ...