Powermockito not mocking URL constructor in URI.toURL() method

105 views
Skip to first unread message

Vikas Gupta

unread,
Apr 16, 2020, 12:52:23 AM4/16/20
to PowerMock
This unit test is failing.

    package com.abc;

    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.powermock.api.mockito.PowerMockito;
    import org.powermock.core.classloader.annotations.PowerMockIgnore;
    import org.powermock.core.classloader.annotations.PrepareForTest;
    import org.powermock.modules.junit4.PowerMockRunner;

    import java.net.URI;
    import java.net.URL;

    import static org.junit.Assert.assertEquals;

    @RunWith(PowerMockRunner.class)
    @PowerMockIgnore("javax.management.*")
    @PrepareForTest({URI.class})
    public class ITest2 {
        @Test
        public void test5() throws Exception {
            URI uri = new URI("http://www.google.com");

            final URL resourceUrl = ClassLoader.getSystemClassLoader().getResource("static/abc.png"); //EXISTS

            PowerMockito.whenNew(URL.class).withArguments(
                    "http://www.google.com")
                    .thenReturn(resourceUrl);

            URL url = uri.toURL(); // <--- At this point, url should be == resourceUrl

            assertEquals(resourceUrl, url); // <--- url is http://www.google.com and not ".../static/abc.png"
        }
    }

This unit test is failing.

    java.lang.AssertionError:
    Expected :file:/Users/hidden/target/classes/static/abc.png
    Actual   :http://www.google.com
    <Click to see difference>

Do you know why url != resourceUrl? What am I missing?

Here's the code of URI.toURL():

    public URL toURL()
        throws MalformedURLException {
        if (!isAbsolute())
            throw new IllegalArgumentException("URI is not absolute");
        return new URL(toString());
    }
Using Mockito 2.15 & Powermock 2.0.7.

Thank you.

Update:

Adding these don't help either. Just hacking away.

    PowerMockito.whenNew(URL.class).withArguments(
            eq("http://www.google.com"))
            .thenReturn(resourceUrl);

    PowerMockito.whenNew(URL.class).withArguments(Mockito.anyString()).thenReturn(resourceUrl);
    PowerMockito.whenNew(URL.class).withArguments(any()).thenReturn(resourceUrl);
    PowerMockito.whenNew("java.net.URL").withArguments(any()).thenReturn(resourceUrl);

    PowerMockito.whenNew(URL.class).withParameterTypes(String.class)
            .withArguments("http://www.google.com")
            .thenReturn(resourceUrl);

    PowerMockito.whenNew(URL.class).withAnyArguments().thenReturn(resourceUrl);

    PowerMockito.whenNew(URL.class).withNoArguments().thenReturn(resourceUrl);


Reply all
Reply to author
Forward
0 new messages