Mocking a URL in Java

前端 未结 10 1700
臣服心动
臣服心动 2020-12-14 08:16

We have a URL object in one of our Java classes that we want to mock, but it\'s a final class so we cannot. We do not want to go a level above, and mock the InputStream beca

10条回答
  •  臣服心动
    2020-12-14 08:40

    I think you can use Powermock to do this. I was able to mock URL class using PowerMock lately. Hope this helps.

    /* Actual class */

    import java.net.MalformedURLException;
    import java.net.URL;
    
    public class TestClass {
    
        public URL getUrl()
            throws MalformedURLException {
    
            URL url = new URL("http://localhost/");
            return url;
        }
    }
    

    /* Test class */

    import java.net.URL;
    
    import junit.framework.Assert;
    
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.mockito.Mockito;
    import org.powermock.api.mockito.PowerMockito;
    import org.powermock.core.classloader.annotations.PrepareForTest;
    import org.powermock.modules.junit4.PowerMockRunner;
    
    @RunWith(PowerMockRunner.class)
    @PrepareForTest(value = { TestClass.class })
    public class TestClassTest {
    
        private TestClass testClass = new TestClass();
    
        @Test
        public void shouldReturnUrl()
            throws Exception {
    
            URL url = PowerMockito.mock(URL.class);
            PowerMockito.whenNew(URL.class).withParameterTypes(String.class)
                    .withArguments(Mockito.anyString()).thenReturn(url);
            URL url1 = testClass.getUrl();
            Assert.assertNotNull(url1);
        }
    }
    

提交回复
热议问题