how to mock a URL connection

前端 未结 6 994
感情败类
感情败类 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:17

    In order to mock java.net.URL class through mockito library, you need to perform the following steps:

    • Create a directory, named 'mockito-extensions' in src/tests/resources directory.
    • Create text a text file in the folder, named org.mockito.plugins.MockMaker and put mock-maker-inline text into the file.
    • you can mock the class like the following:

    code:

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

提交回复
热议问题