当没有接口时、不可继承时,如果使用mock方案进行单元测试

原版代码:

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;
        }
    }
}

 

转载于:https://www.cnblogs.com/junjie2019/p/10623584.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
HttpUrlConnectionJava 标准库中用于发送 HTTP 请求和处理 HTTP 响应的类。它提供了一种简单的方式来与远程服务器进行通信。您可以使用 HttpUrlConnection 类来建立连接、发送请求、读取响应和处理错误。 以下是使用 HttpUrlConnection 发送 GET 请求的示例代码: ```java import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class HttpUrlConnectionExample { public static void main(String[] args) { try { URL url = new URL("http://example.com/api"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); int responseCode = connection.getResponseCode(); System.out.println("Response Code: " + responseCode); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; StringBuilder response = new StringBuilder(); while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); System.out.println("Response: " + response.toString()); connection.disconnect(); } catch (Exception e) { e.printStackTrace(); } } } ``` 这个示例中,我们创建了一个 URL 对象来指定要发送请求的目标 URL。然后,我们打开一个 HttpURLConnection 连接并设置请求方法为 GET。发送请求后,我们可以获取响应码、读取响应内容,并在最后关闭连接。 您可以根据需要设置请求头、添加请求参数等。同,HttpUrlConnection 也支持其他的 HTTP 方法,如 POST、PUT、DELETE 等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值