Java 为单元测试创​​建对象 MockHttpServletResponse 时出错

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23386234/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 22:45:04  来源:igfitidea点击:

Error creating object MockHttpServletResponse for unit testing

javaspringunit-testingmavenmockito

提问by gyanu

  1. I was trying to write unit test for Servlet using sprint-test using mock object

  2. my maven dependency is:

    <dependency>
       <groupId>org.springframework</groupId>
       <artifactId>spring-test</artifactId>
       <version>4.0.3.RELEASE</version>
    </dependency>
    
  1. 我试图使用模拟对象使用 sprint-test 为 Servlet 编写单元测试

  2. 我的Maven依赖是:

    <dependency>
       <groupId>org.springframework</groupId>
       <artifactId>spring-test</artifactId>
       <version>4.0.3.RELEASE</version>
    </dependency>
    

I want to test just java servlet like below following book PRACTICAL TDD AND ACCEPTANCE TDD FOR JAVA DEVELOPER:

我想只测试 Java servlet,如下面的书PRACTICAL TDD AND ACCEPTANCE TDD FOR JAVA DEVELOPER

package sample;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginServlet extends HttpServlet {
    private boolean isValid;

    /**
     * 
     */
    private static final long serialVersionUID = 2473252741884321641L;

    @Override
    public void init() throws ServletException {
        super.init();

    }

    @Override
    public void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws IOException {
        String user = req.getParameter("j_username");
        String pass = req.getParameter("j_password");
        if (isValidLogin(user, pass)) {
            resp.sendRedirect("/frontpage");
            req.getSession().setAttribute("username", user);
        } else {
            resp.sendRedirect("/invalidlogin");
        }

    }

    private boolean isValidLogin(String user, String pass) {
        return isValid;
    }

    public void setValid(boolean isValid) {
        this.isValid = isValid;
    }

}

My code is:

我的代码是:

    package sample;
    import static org.junit.Assert.assertEquals;
    import org.junit.Test;
    import org.springframework.mock.web.MockHttpServletRequest;
    import org.springframework.mock.web.MockHttpServletResponse;

    public class SprintTestProb {

    @Test
    public void wrongPasswordShouldRedirectToErrorPage() throws Exception {
        MockHttpServletRequest request = new MockHttpServletRequest();
        MockHttpServletResponse response = new MockHttpServletResponse();
        request.addParameter("j_username", "gyanu");
        request.addParameter("j_password", "wrongpassword");
        LoginServlet login = new LoginServlet();
        login.setValid(false);
        login.doPost(request, response);
        assertEquals("/invalidlogin", response.getRedirectedUrl());
    }

}

I got error on line MockHttpServletResponse response = new MockHttpServletResponse();as follows:

我在线上出现错误MockHttpServletResponse response = new MockHttpServletResponse(); 如下:

java.lang.ExceptionInInitializerError
    at org.springframework.mock.web.MockHttpServletResponse.<init>(MockHttpServletResponse.java:76)
    at sample.SprintTestProb.wrongPasswordShouldRedirectToErrorPage(SprintTestProb.java:14)
    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:606)
    at org.junit.runners.model.FrameworkMethod.runReflectiveCall(FrameworkMethod.java:47)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:238)
    at org.junit.runners.ParentRunner.schedule(ParentRunner.java:63)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
    at org.junit.runners.ParentRunner.access
<dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>javax.servlet-api</artifactId>
  <version>3.1.0</version>
</dependency>
0(ParentRunner.java:53) at org.junit.runners.ParentRunner.evaluate(ParentRunner.java:229) at org.junit.runners.ParentRunner.run(ParentRunner.java:309) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50) 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) Caused by: java.util.MissingResourceException: Can't find bundle for base name javax.servlet.LocalStrings, locale en_US at java.util.ResourceBundle.throwMissingResourceException(ResourceBundle.java:1499) at java.util.ResourceBundle.getBundleImpl(ResourceBundle.java:1322) at java.util.ResourceBundle.getBundle(ResourceBundle.java:721) at javax.servlet.ServletOutputStream.<clinit>(ServletOutputStream.java:87) ... 25 more

采纳答案by gyanu

I need to replace dependency for javaee-api with javax.selvlet-api as below:

我需要用 javax.selvlet-api 替换 javaee-api 的依赖关系,如下所示:

    @WebAppConfiguration
    @ContextConfiguration
    public class WacTests {

    @Autowired WebApplicationContext wac; // cached

    @Autowired MockServletContext servletContext; // cached

    @Autowired MockHttpSession session;

    @Autowired MockHttpServletRequest request;

    @Autowired MockHttpServletResponse response;

    @Autowired ServletWebRequest webRequest;

    //...
}

回答by Shiraaz.M

According to the Spring Framework Reference for Testingyou should be using annotations to autowire your mocks. The example in the spring reference:

根据Spring Framework Reference for Testing,您应该使用注释来自动装配您的模拟。spring参考中的例子:

`

`

<dependency>
 <groupId>org.mortbay.jetty</groupId>
 <artifactId>servlet-api-2.5</artifactId>
 <version>6.1.11</version>
</dependency>

`

`

A different example (without annotations) can be found here

一个不同的例子(没有注释)可以在这里找到

回答by sina

I had a similar issue and solved it by adding this dependency to my pom and there is no need to change your javaee-api to javax.servlet

我有一个类似的问题,并通过将此依赖项添加到我的 pom 中解决了它,并且无需将您的 javaee-api 更改为 javax.servlet

##代码##