模拟到HTTP连接会产生空指针异常

时间:2018-11-10 22:58:49

标签: java http junit nullpointerexception mocking

我正在尝试模拟我创建的HTTP方法。对于get方法,尝试执行POST \ PUT时测试失败,我得到了null异常。

我将输入部分代码:

public HTTPResult httpPostPutGetRequest(String url, String jsonString, String requestMethod) throws Exception {
    HttpURLConnection connection = connectionFactory.createURLConnection(url);
    connection.setRequestMethod(requestMethod);
    String result = null;
    if (requestMethod == "PUT" || requestMethod == "POST") {

        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Accept", "application/json");

        OutputStreamWriter osw = new OutputStreamWriter(connection.getOutputStream());
        osw.write(String.format(jsonString));
        osw.close();

然后,我尝试通过以下方式对其进行模拟:

public class StepdefsCommonTest {

    private static final int PORT = 51234;
    private static final String baseUrl = "http://localhost:" + PORT;
    private HTTPResult result = null;

    private String responseBody = "{blbl}";
    private String responseMessage = "OK";
    private int responseCode = 200;

    public HTTPResult mockHttpRequest(String httpMethod) throws Exception {

        HttpURLConnection mockHttpURLConnection = mock(HttpURLConnection.class);
        URLConnectionFactory mockURLConnectionFactory = mock(URLConnectionFactory.class);

        ByteArrayInputStream responseBodyInputStream = new ByteArrayInputStream(responseBody.getBytes());
        when(mockHttpURLConnection.getResponseCode()).thenReturn(responseCode);
        when(mockHttpURLConnection.getResponseMessage()).thenReturn(responseMessage);
        when(mockHttpURLConnection.getInputStream()).thenReturn(responseBodyInputStream);
        when(mockURLConnectionFactory.createURLConnection(baseUrl)).thenReturn(mockHttpURLConnection);

        StepdefsCommon common = new StepdefsCommon(mockURLConnectionFactory);

        HTTPResult res = null;

        switch(httpMethod){
            case "POST":case "PUT":
                try {
                    res = common.httpPostPutGetRequest(baseUrl,responseBody,httpMethod);
                } catch (IOException e) {
                    e.printStackTrace();
                }

我收到以下内容的空指针异常: OutputStreamWriter osw = new OutputStreamWriter(connection.getOutputStream()); 我得到的例外情况:

java.lang.NullPointerException
    at java.io.Writer.<init>(Writer.java:88)
    at java.io.OutputStreamWriter.<init>(OutputStreamWriter.java:109)

0 个答案:

没有答案