[JAVA] How to use the wrapper class

Overview

How to use the wrapper class.

When you want to mock the final class

When I was writing test code, I wanted to mock the final class, so I made it a wrapper class. Originally it was a method that took a final class as an argument, but since it can not be tested with that, I decided to take an argument with a wrapper class. Wouldn't this have happened if we had developed test-driven from the beginning? .. .. difficult.

Original code

python



@Override
protected String doInBackground(URL... url) {
    HttpURLConnection con = null;
    URL urls = url[0];

    try {
        con = (HttpURLConnection)urls.openConnection();
        con.setRequestMethod("GET");
        con.connect();

        int resCd = con.getResponseCode();
        if (resCd != HttpURLConnection.HTTP_OK) {
            throw new IOException("HTTP responseCode:" + resCd);
        }

        BufferedInputStream inputStream = new BufferedInputStream(con.getInputStream());
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        String line;
        while (true) {
            line = reader.readLine();
            if (line == null) {
                break;
            }
            mBuffer.append(line);
        }
        inputStream.close();
        reader.close();

    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        con.disconnect();
    }
    return mBuffer.toString();
}

Modified code

python


@Override
protected String doInBackground(URLWrapper... urlWrapper) {
    HttpURLConnection con = null;
    URLWrapper urls = urlWrapper[0];

    try {
        con = (HttpURLConnection)urls.openConnection();
        con.setRequestMethod("GET");
        con.connect();

        int resCd = con.getResponseCode();
        if (resCd != HttpURLConnection.HTTP_OK) {
            throw new IOException("HTTP responseCode:" + resCd);
        }

        BufferedInputStream inputStream = new BufferedInputStream(con.getInputStream());
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        String line;
        while (true) {
            line = reader.readLine();
            if (line == null) {
                break;
            }
            mBuffer.append(line);
        }
        inputStream.close();
        reader.close();

    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        con.disconnect();
    }
    return mBuffer.toString();
}

doInBackground is a method of AsyncTask. It's a subtle change, but at first I took java.net.URL as an argument, but I noticed that the URL is a final class and can not be mocked, so I changed it to a wrapper class. I also tried using PowerMockito, but it didn't work, so I'm using this for now. Now you can run the following test code.

python


@Test
public void test_doInBackground(){

    HttpURLConnection httpURLConnection = null;

    try{

        String rtnXml = "aaaaaaaaaaaa";
        //Mocking HttpURLConnection
        httpURLConnection = mock(HttpURLConnection.class);
        when(httpURLConnection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_OK);
        when(httpURLConnection.getInputStream()).thenReturn(new ByteArrayInputStream(rtnXml.getBytes("utf-8")));

        //URLWrapper mock
        URLWrapper urlWrapper = mock(URLWrapper.class);
        when(urlWrapper.openConnection()).thenReturn(httpURLConnection);

        //ConfirmAsyncListenerImpl mock
        ConfirmAsyncListenerImpl confirmAsyncListener = mock(ConfirmAsyncListenerImpl.class);

        // RestaurantAsync.doInBackground()a test of
        RestaurantAsync restaurantAsync = new RestaurantAsync(confirmAsyncListener);
        assertThat(restaurantAsync.doInBackground(urlWrapper), is("aaaaaaaaaaaa"));


    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        httpURLConnection.disconnect();
    }

}

When I try to mock java.net.URL, I get a compile error, so I found that I can handle it by using a wrapper class.

By the way, the wrapper class is as follows

URLWrapper.java



public class URLWrapper {

    private final URL url;

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

    public URLConnection openConnection(){
        URLConnection urlConnection = null;
        try {
            urlConnection =  this.url.openConnection();
        }catch(IOException e){
            e.printStackTrace();
        }
        return urlConnection;
    }
}

I wonder if there are any differences or disadvantages between taking an argument in the final class and taking it in its wrapper class. I will add it when I understand it again.

Summary

I will add it if I notice it again.

Recommended Posts

How to use the wrapper class
[Java] How to use the File class
[Java] How to use the HashMap class
[Processing × Java] How to use the class
[Java] How to use the Calendar class
How to use java class
How to use the link_to method
How to use the include? method
How to use the form_with method
[Java] How to use LinkedHashMap class
How to use class methods [Java]
[Java] How to use Math class
[Java] How to use the hasNext function
[Rails] How to use the map method
[Java] How to use the toString () method
Studying how to use the constructor (java)
[Processing × Java] How to use the loop
How to use Java Scanner class (Note)
[Processing × Java] How to use the function
How to use Map
How to use with_option
How to use fields_for
How to use java.util.logging
How to use map
How to use collection_select
How to use Twitter4J
How to use active_hash! !!
How to use MapStruct
How to use hidden_field_tag
How to use TreeSet
[How to use label]
How to use identity
How to use hashes
How to use JUnit 5
How to use Dozer.mapper
How to use Gradle
How to use org.immutables
How to use java.util.stream.Collector
How to use VisualVM
How to use Map
How to use the camera module OV7725 (ESP32-WROVER-B)
[Java] How to use FileReader class and BufferedReader class
[Java] How to use Thread.sleep to pause the program
Output of how to use the slice method
How to use the replace () method (Java Silver)
[Ruby basics] How to use the slice method
[Java] How to use Calendar class and Date class
How to use Chain API
[Java] How to use Map
How to use Priority Queuing
[Rails] How to use enum
How to use java Optional
How to use JUnit (beginner)
How to use Ruby return
[Rails] How to use enum
How to use @Builder (Lombok)
[Swift] How to use UserDefaults
How to use Swift UIScrollView
How to use Big Decimal
[Java] How to use Optional ②
[Java] How to use removeAll ()