2013年8月1日星期四

Use junit test springMVC of action appearsjava.lang.NullPointerException

Great God help solve ah

Error:
    java.lang.NullPointerException  
        at cn.com.qzinfo.test.base.JUnitActionBase.excuteAction(JUnitActionBase.java:68) 
        at cn.com.qzinfo.test.example.ExampleActionTest.test(ExampleActionTest.java:21) 
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) 
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 
        at java.lang.reflect.Method.invoke(Method.java:601) 
        at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44) 
        at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15) 
        at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41) 
        at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20) 
        at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28) 
        at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31) 
        at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:73) 
        at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:46) 
        at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:180) 
        at org.junit.runners.ParentRunner.access$000(ParentRunner.java:41) 
        at org.junit.runners.ParentRunner$1.evaluate(ParentRunner.java:173) 
        at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28) 
        at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31) 
        at org.junit.runners.ParentRunner.run(ParentRunner.java:220) 
        at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:46) 
        at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) 
        at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467) 
        at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683) 
        at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390) 
        at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197) 


JUnitActionBase categories:
    package cn.com.qzinfo.test.base;  
     
    import javax.servlet.http.HttpServletRequest; 
    import javax.servlet.http.HttpServletResponse; 
     
    import org.junit.BeforeClass; 
    import org.springframework.mock.web.MockServletContext; 
    import org.springframework.web.context.WebApplicationContext; 
    import org.springframework.web.context.support.XmlWebApplicationContext; 
    import org.springframework.web.servlet.HandlerAdapter; 
    import org.springframework.web.servlet.HandlerExecutionChain; 
    import org.springframework.web.servlet.HandlerMapping; 
    import org.springframework.web.servlet.ModelAndView; 
    import org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter; 
    import org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping; 
     
    /**
     * JUnit测试action时使用的基类
     * 
     * @author fule
     * 
     */ 
     
    public class JUnitActionBase { 
        private static HandlerMapping handlerMapping; 
        private static HandlerAdapter handlerAdapter; 
     
        /**
         * 读取配置文件c
         */ 
        @BeforeClass 
        public static void setUp() { 
            if (handlerMapping == null) { 
                String[] configs = { "file:src/applicationContext.xml","file:WebRoot/WEB-INF/springMVC-servlet.xml" }; 
                XmlWebApplicationContext context = new XmlWebApplicationContext(); 
                context.setConfigLocations(configs); 
                MockServletContext msc = new MockServletContext(); 
                context.setServletContext(msc); 
                context.refresh(); 
                msc 
                        .setAttribute( 
                                WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, 
                                context);// TODO 
                handlerMapping = (HandlerMapping) context 
                        .getBean(DefaultAnnotationHandlerMapping.class); 
     
                handlerAdapter = (HandlerAdapter) context 
                        .getBean(context 
                                .getBeanNamesForType(AnnotationMethodHandlerAdapter.class)[0]); 
     
                // handlerAdapter = (HandlerAdapter) context.getBean(context 
                // .getNamespace()); 
            } 
        } 
     
        /**
         * 执行request请求的action
         * 
         * @param request
         * @param response
         * @return
         * @throws Exception
         */ 
          public ModelAndView excuteAction(HttpServletRequest request, HttpServletResponse response)   
          throws Exception {   
                 HandlerExecutionChain chain = handlerMapping.getHandler(request);   
                 final ModelAndView model = handlerAdapter.handle(request, response,   
                         chain.getHandler());   
                 return model;   
             }  
    } 


test class ;
    package cn.com.qzinfo.test.example;  
     
    import org.junit.Assert; 
    import org.junit.Test; 
    import org.springframework.mock.web.MockHttpServletRequest; 
    import org.springframework.mock.web.MockHttpServletResponse; 
     
    import cn.com.qzinfo.test.base.JUnitActionBase; 
     
    public class ExampleActionTest extends JUnitActionBase { 
     
        @Test 
        public void test() throws Exception { 
            MockHttpServletRequest request = new MockHttpServletRequest(); 
            MockHttpServletResponse response = new MockHttpServletResponse(); 
            request.setRequestURI("example_exampleAction_insetExample"); 
            request.addParameter("operatorId", "1234"); 
            request.addParameter("strRev1", "1234"); 
            request.setMethod("post"); 
             
                this.excuteAction(request, response);   
                // 执行结果   
                String result = response.getContentAsString();   
                Assert.assertNotNull(result);   
        } 
    } 


Action class :
package cn.com.qzinfo.example.action;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import cn.com.qzinfo.example.model.Example;
import cn.com.qzinfo.example.service.ExampleService;

@Controller
@RequestMapping(value = "/example") 
public class ExampleAction {
@Resource
private ExampleService exampleServcie;

@RequestMapping(value = "example_exampleAction_insetExample")
public ModelAndView insertExample(Example example) {
exampleServcie.insertExample(example);
return new ModelAndView("/example/exampleList");
}

}



springMVC-servlet.xml:
    <?xml version="1.0" encoding="UTF-8"?>  
    <beans xmlns="http://www.springframework.org/schema/beans" 
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" 
        xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" 
        xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" 
        xsi:schemaLocation="         
            http://www.springframework.org/schema/beans          
            http://www.springframework.org/schema/beans/spring-beans-3.0.xsd         
            http://www.springframework.org/schema/mvc          
            http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd         
            http://www.springframework.org/schema/context          
            http://www.springframework.org/schema/context/spring-context-3.0.xsd" 
        default-autowire="byName"> 
        <!-- 自动扫描    --> 
        <context:component-scan base-package="cn.com.qzinfo" /> 
        <!-- 使用spring MVC 注解功能   --> 
        <mvc:annotation-driven />      
        <bean 
            class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" /> 
        <!-- 对模型试图层的解析--> 
        <bean 
            class="org.springframework.web.servlet.view.InternalResourceViewResolver" 
            p:prefix="/WEB-INF/jsp/" p:suffix=".jsp"></bean> 
     
    </beans> 

------ Solution ------------------------------------- -------
public ModelAndView excuteAction above without adding @ Test
------ Solution ------------------- -------------------------
encountered the same problem , do not know the landlord did not solve
------ Solution --------------------------------------------
view source, the place is being given

private boolean useTypeLevelMapping(HttpServletRequest request) {
if (!hasTypeLevelMapping() || ObjectUtils.isEmpty(getTypeLevelMapping().value())) {
return false;
}
return (Boolean) request.getAttribute(HandlerMapping.INTROSPECT_TYPE_LEVEL_MAPPING);
}

tracking this method found inside is ultimately DispatcherServlet.class doService method invocation .
This explains why we simulate the request will complain , and we simply do not follow the normal process , so this INTROSPECT_TYPE_LEVEL_MAPPING property setting code and did not execute .
request as long as the simulation before it will HandlerMapping.INTROSPECT_TYPE_LEVEL_MAPPING set to true on the line.
request.setAttribute (HandlerMapping.INTROSPECT_TYPE_LEVEL_MAPPING, true);
------ For reference only --------------------- ------------------
/ / here you need to declare the actual type of request , otherwise it will error
request.setAttribute (HandlerMapping.INTROSPECT_TYPE_LEVEL_MAPPING, true);

没有评论:

发表评论