1

I have written a simple method in my controller as part of my Java Spring Boot Application which works without issue using and I have tested it using Postman. However I am unsure how to unit test this using Junit and Mockito. I have shown a snippet of my code below, first is my Controller.java class and then my test is within a ControllerTest.java. How can I unit test this correctly?

EDIT: I know my test case is the problem, I have removed it as all comments are focusing on why it is wrong. I am asking how do I write a unit test case for this specific saveCase method.

I have already tried looking at examples from below links Rest Controller Unit Test Spring RestController + Junit Testing

@Autowired
Service service;

@PostMapping("/savecase")
public ResponseEntity<PIECase> saveCase(@Valid @RequestBody PIECase pieCase) {
    return ResponseEntity.ok(pieService.saveCase(pieCase));
}
Coder
  • 197
  • 1
  • 17
  • *"can't seem to get the correct result"* What is the "correct" result? What is the actual result? – Michael Aug 23 '19 at 13:10
  • The test is supposed to verify that the controller works as it should, i.e. returns a PIECase object serialized to JSON. But your test checks that the response is `"some expected response"`. To make it simpler, you test is the equivalent of testing that a service adding 2 to 3 return 42. The test is the problem. – JB Nizet Aug 23 '19 at 13:35

1 Answers1

0

You need to Mock all service which is calling inside your Restcontroller so will not get Nullpointer exception

RunWith(MockitoJUnitRunner.class) declaration which will cause @Mock and @InjectMocks annotation to work automatically without any explicit initialization

 package com.khan.vaquar.controller;

import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.json.JSONException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.owasp.esapi.errors.IntrusionException;
import org.owasp.esapi.errors.ValidationException;
import org.springframework.beans.factory.annotation.Autowired;

import com.fasterxml.jackson.core.JsonProcessingException;


@RunWith(MockitoJUnitRunner.class)
public class RestControllerTest {

    private static Logger log = Logger.getLogger(RestControllerTest.class.getName());

    @InjectMocks
    private RestController restController;


    @Mock
    private RestServiceImpl restServiceImpl;

    @Mock
    private RestResponseBuilder restResponseBuilder;

    @Mock
    private HttpServletRequest request;

    @Autowired
    RuleEngine ruleEngine;

     @Test
    public void testRestControllereFlow() throws Exception {


        String inputJson="{  \r\n" + 
                "   \"Data\":{  \r\n" + 
                "      \"personalInfo\":{  \r\n" + 
                "         \"User\":{  \r\n" + 
                "           \"email\":\"vaquar.khan@gmail.com\",\r\n" + 
                "           \"name\": \"vaquar khan\"\r\n" + 
                "          
                "        , }}+ 
                "}";
        Response response =null;
        try {
            response=restController.restControllerMethd(inputJson);
            }catch(Exception e){
        //      e.printStackTrace();
            }
        assertNotNull(response);

    }
    }
vaquar khan
  • 10,864
  • 5
  • 72
  • 96