简体   繁体   English

MockMvc Sp​​ring null指针

[英]MockMvc Spring null Pointer

Hi I am new to the Spring test framework and I have the following code Spring MVC Controller to test: 嗨,我是Spring测试框架的新手,我有以下代码Spring MVC Controller来测试:

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: 请在控制器中找到以下字段和initBinder方法定义:

  @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: 这是我的单元测试,我也在使用Mockito:

@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: 这是第117行:

 mockMvc.perform(

I am not sure what is null here any idea how to solve this please? 我不知道什么是null这里有任何想法如何解决这个问题?

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. 提前感谢任何建议。

Although the original problem was reported years ago, I ran into the same issue - a NullPointerException on mockMvc.perform() 虽然几年前报告了原始问题,但我遇到了同样的问题 - mockMvc.perform()上的NullPointerException

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. 经过大量的调试后,我发现我编写的用于验证我的请求的自定义JWT过滤器中有一个Null Pointer问题,它在perform()方法本身被报告为NullPointerException。

Once I fixed my filter to avoid the null pointer exception, everything started working. 一旦我修复我的过滤器以避免空指针异常,一切都开始工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM