unit-testing - Spring REST 离线测试

标签 unit-testing spring spring-mvc

我正在尝试测试 Spring Web MVC Controller 。

我有以下测试类:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:controller-test.xml" })
public class EmployeesControllerMockTest implements ApplicationContextAware {


    // this servlet is going to be instantiated by ourselves
    // so that we can test the servlet behaviour w/o actual web container
    // deployment
    protected DispatcherServlet servlet;


    // we need to get at the context already loaded via the @ContextConfiguration annotation.
    protected ApplicationContext appCtx;

    public void setApplicationContext(ApplicationContext applicationContext)
                    throws BeansException {
        appCtx = applicationContext;
    }

    /**
     * using @Before is convenient, but with JUnit these annotated methods must be public (not like e.g. testNG)
     * so be aware that no "secrets" are being set/got in these init-style methods ;_)! !
     */
    @Before
    public void initDispatcherServlet() {
        servlet = new DispatcherServlet() {
                @Override
                protected WebApplicationContext createWebApplicationContext(
                                WebApplicationContext parent) throws BeansException {

                        GenericWebApplicationContext gwac = new GenericWebApplicationContext();
                        gwac.setParent(appCtx);
                        gwac.refresh();
                        return gwac;
                }
        };
    }

    @Test
    public void test() {
        MockHttpServletRequest request = new MockHttpServletRequest("GET", "/employees/test");
        MockHttpServletResponse response = new MockHttpServletResponse();
        try {
            servlet.service(request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println(response.getStatus());
    }
}

还有我的controller-test.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:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:oxm="http://www.springframework.org/schema/oxm"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
                http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
                http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-3.0.xsd
                http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

    <!-- Force the Spring container to search the controller package for all stereotype components. Detect all 
    components marked with the @Controller annotations in the scan. -->
    <context:component-scan base-package="controller" />

    <!-- Enable automatic annotation-driven declaration. Configure the @Controller programming model -->
    <mvc:annotation-driven/>

</beans>

但是我在 servlet.service() 调用中遇到以下异常:

java.lang.NullPointerException
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:682)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
    at tests.controller.EmployeesControllerMockTest.test(EmployeesControllerMockTest.java:68)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    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.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:82)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:240)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:180)
    at org.apache.maven.surefire.junit4.JUnit4TestSet.execute(JUnit4TestSet.java:35)
    at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:115)
    at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:97)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.apache.maven.surefire.booter.ProviderFactory$ClassLoaderProxy.invoke(ProviderFactory.java:103)
    at $Proxy0.invoke(Unknown Source)
    at org.apache.maven.surefire.booter.SurefireStarter.invokeProvider(SurefireStarter.java:150)
    at org.apache.maven.surefire.booter.SurefireStarter.runSuitesInProcess(SurefireStarter.java:91)
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:69)

我做错了什么吗?

最佳答案

您无需在测试中花费所有精力来配置 servlet - Spring MVC Controller 可以直接进行单元测试。 Controller 不依赖于 servlet,因此 servlet 对于您的单元测试来说是多余的。

只需在测试中创建 Controller 对象,并根据需要将请求/响应对象传递给它。

如果您想测试 servlet、 Controller 和配置之间的交互,那么您应该在 servlet 容器内进行此操作,作为功能测试。

关于unit-testing - Spring REST 离线测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6106979/

相关文章:

typescript ,单元测试 : Correct typing for Dispatching a Thunk with store. 从 redux-mock-store 发送

spring - 无法在 Spring Boot 启动时执行 data.sql 和 schema.sql

java - 如何隐式选择viewResolver

java - 服务层私有(private)方法

java - 寻找一本涵盖单元、功能、集成和场景测试的综合 Java 测试书籍

Android Studio : Instrument Tests Cannot Find junit, mockito 或 hamcrest

spring - 如何使用 Spring Security 为微服务创建自定义安全过滤器

java - Spring上传多个文件如何识别每个文件?

java - 如何使用restful服务返回json数组

spring - spring 请求映射和 url 映射有什么区别?