how to mock a URL connection

前端 未结 6 978
感情败类
感情败类 2020-12-06 01:50

Hi I have a method that takes an URL as an input and determines if it is reachable. Heres the code for that:

public static boolean isUrlAccessible(final Str         


        
6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-06 02:31

    Although this thread has some good suggestion, but if any of you is not interested to use those third-party libraries here is a quick solution.

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

    And, this how you can set the desired behaviour

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

    Note: It just mock 3 methods from HttpUrlConnection and if you are using more method you need to make sure those are mock as well.

提交回复
热议问题