3

I have a class named Pinger Service which calls a HttpAdapter opening up HttpURLConnection and returning it, where getResponseCode is then called to find out if the URL was 200 or not.

I am attempting to mock HttpURLConnection and make getResponseCode return a 404, however I am getting a Null Pointer Exception

Tests

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 Service

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;
    }
}

HttpAdapter

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;
    }
}

Failure trace

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)
Jacob Clark
  • 3,317
  • 5
  • 32
  • 61
  • Please provide stacktrace – mariusz2108 Apr 25 '16 at 18:34
  • @ManoDestra No, how? This is clearly related to Mockito and my spring beans not being injected correctly. – Jacob Clark Apr 25 '16 at 18:42
  • Your tests are making large assumptions that they have each object (non null) returned from the previous call. It's a simple matter of checking each object returned to see which one is null. And the stack trace tells you precisely where it is occurring: `PingerServiceTests.java:44` – ManoDestra Apr 25 '16 at 18:45
  • Take a look at the test class in this example, I don't think you should be using Autowired annotation in a test class. You should use @InjectMocks instead. http://stackoverflow.com/questions/36167148/criteria-query-mockito-unit-test-nullpointerexception – Arun Apr 25 '16 at 19:09

4 Answers4

5

You run you test using SpringJUnit4ClassRunner and as far as I know, @Mock doesn't work unless you use MockitoJunitRunner or MockitoAnnotations.initMocks(this);.

Also note that there's nothing in your code that makes your service use your mocks.

That's why you get a NPE, because mockHttpURLConnection is null in your test method.

  • Adding MockitoAnnotations.initMocks(this); worked, my tests seem to be using my mocks, how would I go about explicitly telling my service to use my mocks? @InjectMocks annotation on the service? – Jacob Clark Apr 25 '16 at 18:50
  • Not sure about `@InjectMock`, a good old setter will do the job –  Apr 25 '16 at 18:51
  • Yes @InjectMocks is for exactly the same purpose to use all the Mock objects – Arun Apr 25 '16 at 18:56
  • Then shouldn't this answer be marked as correct? – Marco Tedone Apr 25 '16 at 21:28
1

The url value you are using to stub the HttpUrlConnection creation from HttpAdapter i.e call to httpAdapter.createHttpURLConnection doesnt match the value you are passing to pingerService.ping. devnews.today != http://devnews.today

Check these two lines

Mockito.when(httpAdapter.createHttpURLConnection("devnews.today")).thenReturn(mockHttpURLConnection);

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

Hence at runtime HttpUrlConnection is actually null wthe default return value for mocks

ekem chitsiga
  • 5,523
  • 2
  • 17
  • 18
1

Instead of @Autowire on PingerService use @InjectMocks

Then, (since you are using SpringJUnit4ClassRunner.class) add a method annotated with @Before. And Inside that method write MockitoAnnotations.initMocks(this)

If you don't want to use MockitoAnnotations.initMocks(this), you can use MockitoJunitRunner

import com.uk.jacob.SimplePingApplication;
import com.uk.jacob.adapter.HttpAdapter;
import com.uk.jacob.model.Website;
import org.mockito.InjectMocks;
import org.mockito.MockitoAnnotations;

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

    @InjectMocks
    PingerService pingerService;

    @Mock
    HttpAdapter httpAdapter;

    @Mock
    HttpURLConnection mockHttpURLConnection;


    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
    }    

    @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);
    }

}
A0__oN
  • 8,740
  • 6
  • 40
  • 61
0
Try this and change @Autowired to @InjectMocks in test class.


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

    Mockito.when(mockHttpURLConnection.getResponseCode()).thenReturn(404);

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

            assertEquals(false, website.ok);
        }
Arun
  • 2,312
  • 5
  • 24
  • 33