java - JUnit 和 Mockito 空指针异常

标签 java spring junit spring-boot

<分区>

我有一个名为 Pinger Service 的类,它调用一个 HttpAdapter 打开 HttpURLConnection 并返回它,然后调用 getResponseCode 来确定 URL 是否为 200。

我正在尝试模拟 HttpURLConnection 并使 getResponseCode 返回 404,但是我得到了空指针异常

测试

package com.uk.jacob.service;

import static org.junit.Assert.*;

import java.io.IOException;
import java.net.HttpURLConnection;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;

import com.uk.jacob.SimplePingApplication;
import com.uk.jacob.adapter.HttpAdapter;
import com.uk.jacob.model.Website;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = SimplePingApplication.class)
@WebAppConfiguration
public class PingerServiceTests {

    @Autowired
    PingerService pingerService;

    @Mock
    HttpAdapter httpAdapter;

    @Mock
    HttpURLConnection mockHttpURLConnection;

    @Test
    public void testPingerServiceReturnsOkWhenServiceIsUp() throws IOException{
        Website website = pingerService.ping("http://devnews.today");

        assertEquals(true, website.ok);
    }

    @Test
    public void testPingerServiceReturnsOkWhenServiceIsNotFound() throws IOException{
        Mockito.when(mockHttpURLConnection.getResponseCode()).thenReturn(404);
        Mockito.when(httpAdapter.createHttpURLConnection("http://devnews.today")).thenReturn(mockHttpURLConnection);

        Website website = pingerService.ping("http://devnews.today");

        assertEquals(false, website.ok);
    }

    @Test
    public void testPingerServiceReturnsOkWhenServiceIsDown(){
        Website website = pingerService.ping("https://jacob.uk.comz");

        assertEquals(false, website.ok);
    }

}

Pinger 服务

package com.uk.jacob.service;

import java.net.HttpURLConnection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.uk.jacob.adapter.HttpAdapter;
import com.uk.jacob.model.Website;

@Component
public class PingerService {

    @Autowired
    HttpAdapter httpAdapter;

    @Autowired
    Website website;

    public Website ping(String urlToPing) {     
        try {
            HttpURLConnection connection = httpAdapter.createHttpURLConnection(urlToPing);

            System.out.println(connection.getResponseCode());

            if(connection.getResponseCode() == 200){
                website.ok = true;
            }
        } catch (Exception e) {
            website.ok = false;
        }

        return website;
    }
}

HTTP适配器

package com.uk.jacob.adapter;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

import org.springframework.stereotype.Component;

@Component
public class HttpAdapter {
    public HttpURLConnection createHttpURLConnection(String urlToPing) throws IOException{
        URL url = new URL(urlToPing);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        connection.setRequestMethod("GET");
        connection.connect();

        return connection;
    }
}

故障轨迹

java.lang.NullPointerException
    at com.uk.jacob.service.PingerServiceTests.testPingerServiceReturnsOkWhenServiceIsNotFound(PingerServiceTests.java:44)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:254)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:193)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

最佳答案

您使用 SpringJUnit4ClassRunneras far as I know 运行您的测试, @Mock 不起作用,除非您使用 MockitoJunitRunnerMockitoAnnotations.initMocks(this);

另请注意,您的代码中没有任何内容会使您的服务使用您的模拟。

这就是您获得 NPE 的原因,因为 mockHttpURLConnection 在您的测试方法中为 null。

关于java - JUnit 和 Mockito 空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36848303/

相关文章:

java - Kafka 0.10.2 消费者获得大量重复项

java - Spring:如何获取bean层次结构?

java - Spring - 如何将组件从另一个模块注入(inject)到 SpringBoot 应用程序中

java - 按指定顺序运行 Maven 项目的 JUnit 测试

java - 无法从 SOAP 网络服务打印 XML 响应

java - Weblogic 没有 [javax.persistence.EntityManager] 类型的唯一 bean

java - 如何获取回收者 View 中所有项目的总数

java - 从 WebSphere 迁移到 Tomcat 7,未定义 [com.m.g.tenancy.ITenantPlaceholderResolver] 类型的唯一 bean : expected single bean but found 0

java - 如何为此 "FileNotFoundException"编写Junit测试

java - jMockit:如何期望构造函数调用模拟对象?