1

I am trying to test my code which parses a JSON response from a URL.

This is the code I'm trying to test:

    public String getJsonResponseFromUrl(String url) {
        JSONObject jsonObject = null;
        try {
            URL apiUrl = new URL(url);
            jsonObject = new JSONObject(IOUtils.toString(apiUrl, StandardCharsets.UTF_8));
        } catch (IOException e) {
            System.out.println(e);
        }
        return jsonObject.toString();
    }

This is the Junit test that I have setup:

import java.net.URL;
import org.json.JSONObject;

@RunWith(MockitoJUnitRunner.class)
@PrepareForTest({URL.class, Service.class, JSONObject.class})
public class ServiceTest {

    private JSONObject mockJsonObject;

    private URL mockUrl;

    @InjectMocks
    private Service mockService;

    @Before
    public void setUp() throws Exception {
        mockJsonObject = PowerMockito.mock(JSONObject.class);
        mockUrl = PowerMockito.mock(URL.class);
    }

    @Test
    public void testGetJsonResponseFromUrl() throws Exception {
        String url = "http://some-url.com"
        PowerMockito.whenNew(URL.class).withArguments(url).thenReturn(mockUrl);
        PowerMockito.whenNew(JSONObject.class).withAnyArguments().thenReturn(mockJsonObject);

        mockService.getJsonResponseFromUrl(url);
    }

}

The problem happens with the mocked URL object.

mockUrl = PowerMockito.mock(URL.class);

When the setUp method hits that line, I get this error in console:

java.lang.RuntimeException: java.lang.reflect.InaccessibleObjectException: Unable to make protected final java.lang.Class java.lang.ClassLoader.defineClass(java.lang.String,byte[],int,int,java.security.ProtectionDomain) throws java.lang.ClassFormatError accessible: module java.base does not "opens java.lang" to unnamed module @593634ad

From what I understand, PowerMockito does allow you to mock final classes like the URL class.

I don't know if there is just something I'm overlooking here.

PowerMockito version: 2.0.9 Junit version: 4.12

Thanks.

EDIT: I realize that the test in this class isn't actually testing anything (i.e. there are no assertions). I made this test to first check that everything was getting mocked correctly.

Shaun Aran
  • 123
  • 4
  • 17
  • What is the point in Mocking `URL`? This method does not provide any logic that might need testing, just configuration. BTW: are you aware that this code throws a NPE when `JSONObject` trows its `IOException`? – Timothy Truckle Dec 20 '21 at 10:13

0 Answers0