How to taunt a URL connection

Hi I have a method that takes a url as input and determines if it is accessible. Here is the code for this:

public static boolean isUrlAccessible(final String urlToValidate) throws WAGNetworkException {
        URL url = null;
        HttpURLConnection huc = null;
        int responseCode = -1;
        try {
            url = new URL(urlToValidate);
            huc = (HttpURLConnection) url.openConnection();
            huc.setRequestMethod("HEAD");
            huc.connect();
            responseCode = huc.getResponseCode();
        } catch (final UnknownHostException e) {
            throw new WAGNetworkException(WAGConstants.INTERNET_CONNECTION_EXCEPTION);
        } catch (IOException e) {
            throw new WAGNetworkException(WAGConstants.INVALID_URL_EXCEPTION);
        } finally {
            if (huc != null) {
                huc.disconnect();
            }
        }
        return responseCode == 200;
    }

I want the unit test method isUrlAccessible () using PowerMockito. I feel that I will need to use whenNew()to make fun of the creation URLand when called url.openConnection(), return another mock HttpURLConnectionobject. But I'm not sure how to implement this? Am I on the right track? Can someone help me in implementing this?

+7
source share
6 answers

. URL-, Mock HttpURLConnection url.openconnection(), HttpURLConnection , , 200. :

@Test
    public void function() throws Exception{
        RuleEngineUtil r = new RuleEngineUtil();
        URL u = PowerMockito.mock(URL.class);
        String url = "http://www.sdsgle.com";
        PowerMockito.whenNew(URL.class).withArguments(url).thenReturn(u);
        HttpURLConnection huc = PowerMockito.mock(HttpURLConnection.class);
        PowerMockito.when(u.openConnection()).thenReturn(huc);
        PowerMockito.when(huc.getResponseCode()).thenReturn(200);
        assertTrue(r.isUrlAccessible(url));

    }
+5

Url

whenNew(URL.class)..

, mock- , .

URL mockUrl = Mockito.mock(URL.class);
whenNew(URL.class).....thenReturn(mockUrl );

, .

+1

URL . , PowerMockito Junit. , Test @RunWith (PowerMockRunner.class) @PrepareForTest ({URL.class})


@RunWith(PowerMockRunner.class) 
@PrepareForTest({ URL.class })
public class Test {
    @Test
    public void test() throws Exception {
        URL url = PowerMockito.mock(URL.class);
        HttpURLConnection huc = Mockito.mock(HttpURLConnection.class);
        PowerMockito.when(url.openConnection()).thenReturn(huc);
        assertTrue(url.openConnection() instanceof HttpURLConnection);
    }
}

PowerMockito.when(url.openConnection()). ThenReturn (huc); :

java.lang.AbstractMethodError
    at java.net.URL.openConnection(URL.java:971)
    at java_net_URL$openConnection.call(Unknown Source) 

, Test, :

@RunWith(PowerMockRunner.class) 
@PrepareForTest({ URL.class })
public class Test {
    @Test
    public void test() throws Exception {

        public class UrlWrapper {

            URL url;

            public UrlWrapper(String spec) throws MalformedURLException {
                url = new URL(spec);
            }

            public URLConnection openConnection() throws IOException {
                return url.openConnection();
            }
        }

        UrlWrapper url = Mockito.mock(UrlWrapper.class);
        HttpURLConnection huc = Mockito.mock(HttpURLConnection.class);
        PowerMockito.when(url.openConnection()).thenReturn(huc);
        assertTrue(url.openConnection() instanceof HttpURLConnection);
    }
}

: https://programmingproblemsandsolutions.blogspot.com/2019/04/abstractmethoderror-is-thrown-on.html

+1

mockito java.net.URL mockito, :

  • 'mockito-extensions' src/tests/resources.
  • org.mockito.plugins.MockMaker mock-maker-inline.
  • , :

:

package myproject;

import org.junit.Test;

import java.net.HttpURLConnection;
import java.net.URL;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;

public class Test {
    @Test
    public void test() throws Exception {
        URL url = mock(URL.class);
        HttpURLConnection huc = mock(HttpURLConnection.class);
        when(url.openConnection()).thenReturn(huc);
        assertTrue(url.openConnection() instanceof HttpURLConnection);
    }
}
0

API JMockit ( ):

import java.io.*;
import java.net.*;
import org.junit.*;
import static org.junit.Assert.*;
import mockit.*;

public final class ExampleURLTest {
   public static final class ClassUnderTest {
      public static boolean isUrlAccessible(String urlToValidate) throws IOException {
         HttpURLConnection huc = null;
         int responseCode;

         try {
            URL url = new URL(urlToValidate);
            huc = (HttpURLConnection) url.openConnection();
            huc.setRequestMethod("HEAD");
            huc.connect();
            responseCode = huc.getResponseCode();
         }
         finally {
            if (huc != null) {
               huc.disconnect();
            }
         }

         return responseCode == 200;
      }
   }

   // Proper tests, no unnecessary mocking ///////////////////////////////////////

   @Test
   public void checkAccessibleUrl() throws Exception {
      boolean accessible = ClassUnderTest.isUrlAccessible("http://google.com");

      assertTrue(accessible);
   }

   @Test(expected = UnknownHostException.class)
   public void checkInaccessibleUrl() throws Exception {
      ClassUnderTest.isUrlAccessible("http://inaccessible12345.com");
   }

   @Test
   public void checkUrlWhichReturnsUnexpectedResponseCode(
      @Mocked URL anyURL, @Mocked HttpURLConnection mockConn
   ) throws Exception {
      new Expectations() {{ mockConn.getResponseCode(); result = -1; }};

      boolean accessible = ClassUnderTest.isUrlAccessible("http://invalidResource.com");

      assertFalse(accessible);
   }

   // Lame tests with unnecessary mocking ////////////////////////////////////////

   @Test
   public void checkAccessibleUrl_withUnnecessaryMocking(
      @Mocked URL anyURL, @Mocked HttpURLConnection mockConn
   ) throws Exception {
      new Expectations() {{ mockConn.getResponseCode(); result = 200; }};

      boolean accessible = ClassUnderTest.isUrlAccessible("http://google.com");

      assertTrue(accessible);
   }

   @Test(expected = UnknownHostException.class)
   public void checkInaccessibleUrl_withUnnecessaryMocking(
      @Mocked URL anyURL, @Mocked HttpURLConnection mockConn
   ) throws Exception {
      new Expectations() {{ mockConn.connect(); result = new UnknownHostException(); }};

      ClassUnderTest.isUrlAccessible("http://inaccessible12345.com");
   }
}

( JMockit 1.47 JDK 8 9.)

0

, - , .

public class MockHttpURLConnection extends HttpURLConnection {
    private int responseCode;
    private URL url;
    private InputStream inputStream;


    public MockHttpURLConnection(URL u){
        super(null);
        this.url=u;
    }
    @Override
    public int getResponseCode() {
        return responseCode;
    }


    public void setResponseCode(int responseCode) {
        this.responseCode = responseCode;
    }

    @Override
    public URL getURL() {
        return url;
    }

    public void setUrl(URL url) {
        this.url = url;
    }

    @Override
    public InputStream getInputStream() {
        return inputStream;
    }

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

    @Override
    public void disconnect() {

    }

    @Override
    public boolean usingProxy() {
        return false;
    }

    @Override
    public void connect() throws IOException {

    }
}

,

   MockHttpURLConnection httpURLConnection=new MockHttpURLConnection(new URL("my_fancy_url"));
        InputStream stream=new ByteArrayInputStream(json_response.getBytes());
        httpURLConnection.setInputStream(stream);
        httpURLConnection.setResponseCode(200);

: HttpUrlConnection 3 HttpUrlConnection , , .

0

All Articles