'Java.lang.NullPointerException when running test cases in Junit for microservices API Requests

Test class :

@RunWith(MockitoJUnitRunner.class)

@TestPropertySource("/application.properties")

@AutoConfigureMockMvc

@SpringBootTest

@WebMvcTest(PensionerDetailController.class)

public class FirstTest {

@Autowired

private MockMvc mockMvc;

@Test

public void testgetmethod() throws Exception{

MvcResult m=mockMvc.perform(MockMvcRequestBuilders.get("/"))

.andExpect(status().isOk()).andReturn();

ModelAndView mw =m.getModelAndView();

ModelAndViewAssert.assertViewName(mw, "Hello, World");

}

}

Controller class:

package com.pensionmanagement.pensionerdetail.controller;

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

import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.bind.annotation.RequestParam;

import org.springframework.web.bind.annotation.ResponseBody;

import org.springframework.web.bind.annotation.RestController;

import com.pensionmanagement.pensionerdetail.model.PensionerDetail;

import com.pensionmanagement.pensionerdetail.service.PensionerDetailService;

@RestController

public class PensionerDetailController {

@Autowired

private PensionerDetailService pensionerDetailService;

@RequestMapping(value = "/", method = RequestMethod.GET)

public String greeting() {

return "Hello, World";

}

@GetMapping("/PensionerDetailByAadhaar")

public PensionerDetail pensionerDetailByAadhaar(@RequestParam Long aadhaarNumber){

return pensionerDetailService.getPensionerDetails(aadhaarNumber);

//BankDetail bank = new BankDetail("Abc", 1231l, "public");

//return new PensionerDetail(123l,"Raagavi","04/02/1999","sf23",BigDecimal.ONE,BigDecimal.ONE,"Self",bank);

}

public String getm()

{

return "hello";

}

}

Result:

java.lang.NullPointerException

at com.pensionmanagement.pensionerdetail.FirstTest.testgetmethod(FirstTest.java:71)



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source