2

Hi I am new to the Spring test framework and I have the following code Spring MVC Controller to test:

public ModelAndView viewChangePassword(ModelMap model, Principal principal, HttpServletRequest request) throws NSException, SQLException {
        System.err.println("testing");
        String name = principal.getName();

        .....

        }

Please find below fields and initBinder method define in the controller:

  @Autowired
    private MessageSource msg;
    @Autowired
    private ApplicationMa applicationMa;
    @Autowired
    private SesVal sesVal;
    @Autowired
    private CommonManager commonManager;
    @Autowired
    private ApplicationListManager applicationListManager;
    @Autowired
    private QueryManager queryManager;
    @Autowired
    private Manager manager;
    @Autowired
    private FormBlankValidator formValidator;

    @Autowired
    private FormDataValidator dataValidator;

    @InitBinder
    protected void initBinder(HttpServletRequest request, WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat(Constants.DD_M_MYYYY);
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }

This is my unit test and I am using Mockito also:

@RunWith(MockitoJUnitRunner.class)
    public class ApplicationControllerTest {

    @InjectMocks
    private ApplicationController appController;
    @Mock
    Principal principal;

    @Mock
     private RequestAttributes requestAttributes;

     @Mock
     private SessionValidator sessionValidator;
     @Mock
     User user;



    private MockMvc mockMvc;


    @Before
    public void setup() {

        // Process mock annotations
        //MockitoAnnotations.initMocks(this);



        // Setup Spring test in standalone mode
        RequestContextHolder.setRequestAttributes(requestAttributes);
        this.mockMvc = MockMvcBuilders.standaloneSetup(appController).build();

    }   


   @Test
    public void viewChangePassword() throws Exception{

       MockHttpServletRequest request = new MockHttpServletRequest();

        when(principal.getName()).thenReturn("user1");
        when(sessionValidator.isSessionValid(user)).thenReturn(true);



        mockMvc.perform(
                get("/viewChangePassword"))
                .andExpect(view().name("denied")                
                );

     }

When I run my unit test the following null pointer exception is shown:

Running com.controller.application.test.ApplicationControllerTest
log4j:WARN No appenders could be found for logger (org.springframework.core.env.StandardEnvironment).
log4j:WARN Please initialize the log4j system properly.
testing
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 1.063 sec <<< FAILURE! - in com.controller.application.test.ApplicationControllerTest
viewChangePassword(com.controller.application.test.ApplicationControllerTest)  Time elapsed: 0.688 sec  <<< ERROR!
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
    at com.controller.application.test.ApplicationControllerTest.viewChangePassword(ApplicationControllerTest.java:117)
Caused by: java.lang.NullPointerException
    at com.controller.application.test.ApplicationControllerTest.viewChangePassword(ApplicationControllerTest.java:117)


Results :

Tests in error: 
  ApplicationControllerTest.viewChangePassword:117 » NestedServlet Request proce...

Tests run: 1, Failures: 0, Errors: 1, Skipped: 0

------------------------------------------------------------------------
BUILD FAILURE
------------------------------------------------------------------------
Total time: 4.423 s

This is line 117:

 mockMvc.perform(

I am not sure what is null here any idea how to solve this please?

Just to point out in the same class this method is working fine with no issue:

   @Test
     public void defaultPageTestOK() throws Exception{
        mockMvc.perform(get("/"))
                .andExpect(redirectedUrl("/view"))  
                .andExpect(status().isFound()

                );

    }

Thanks in advance for any advice.

user1999453
  • 1,297
  • 4
  • 29
  • 65
  • Is it the right `@Before` annotation: `org.junit.Before` but not `org.aspectj.lang.annotation.Before` (or some else)? – Ralph Apr 28 '16 at 08:02
  • yes it is org.junit.Before – user1999453 Apr 28 '16 at 08:07
  • did you check here? http://stackoverflow.com/questions/20978535/testing-spring-mvc-router-with-mockmvc – Deendayal Garg Apr 28 '16 at 08:09
  • checked it but still the same error after adding the header – user1999453 Apr 28 '16 at 09:15
  • What fields and constructor does your ApplicationController have? – dunni Apr 28 '16 at 09:40
  • Add he full stack trace not a snippet. One thing that is missing is you have a mock `Principal` but are nowhere using that in your call to `MockMvc`... So I'm not sure how you think that mocked `Principal` magically appears in your controller.. – M. Deinum Apr 28 '16 at 09:54
  • Hi i manage to find out the issue basically the null pointer was in my method viewChangePassword but it was showing line 117 which was misleading. Thanks a lot for the response – user1999453 Apr 28 '16 at 10:28
  • What was the error in viewChangePassword? – mrks_ Nov 03 '16 at 20:22

1 Answers1

2

Although the original problem was reported years ago, I ran into the same issue - a NullPointerException on mockMvc.perform()

After a lot of debugging, I discovered that the custom JWT filter I had written to authenticate my request had a Null Pointer problem within it, which was being reported as a NullPointerException on the perform() method itself.

Once I fixed my filter to avoid the null pointer exception, everything started working.

johnbr
  • 589
  • 3
  • 7