java.lang.AssertionError - 使用 Mockito 测试 servlet 时出现异常

java.lang.AssertionError - Exception while testing servlet using Mockito

我正在尝试使用 Mockito 测试 servlet 并看到以下异常。不知道为什么 response.getStatus() 方法会 return 0 而不是 200 甚至 response.getContentType() 是 returning null.

异常

Running com.study.mockito.controllers.WelcomeControllerTest
Into the WelcomeController...
response.getStatus() = 0
Tests run: 1, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 0.27 sec <<< FAILURE!
testProcessRequest(com.study.mockito.controllers.WelcomeControllerTest)  Time elapsed: 0.23 sec  <<< FAILURE!
java.lang.AssertionError: expected:<text/html> but was:<null>
    at org.junit.Assert.fail(Assert.java:93)
    at org.junit.Assert.failNotEquals(Assert.java:647)
    at org.junit.Assert.assertEquals(Assert.java:128)
    at org.junit.Assert.assertEquals(Assert.java:147)
    at com.study.mockito.controllers.WelcomeControllerTest.testProcessRequest(WelcomeControllerTest.java:43)
    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:45)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
    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.runners.ParentRunner.runLeaf(ParentRunner.java:263)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:231)
    at org.junit.runners.ParentRunner.schedule(ParentRunner.java:60)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
    at org.junit.runners.ParentRunner.access[=11=]0(ParentRunner.java:50)
    at org.junit.runners.ParentRunner.evaluate(ParentRunner.java:222)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
    at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:252)
    at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:141)
    at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:112)
    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.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189)
    at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165)
    at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85)
    at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:115)
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:75)


Results :

Failed tests:   testProcessRequest(com.study.mockito.controllers.WelcomeControllerTest): expected:<text/html> but was:<null>

WelcomeControllerTest.java

public class WelcomeControllerTest {

    private HttpServletRequest request;
    private HttpServletResponse response;
    private WelcomeController controller;
    private RequestDispatcher rd;
    private ServletContext appContext;

    @Before
    public void setUp() {
        controller = new WelcomeController();
        request = mock(HttpServletRequest.class);
        response = mock(HttpServletResponse.class);
        rd = mock(RequestDispatcher.class);
        appContext = mock(ServletContext.class);
    }

    @Test
    public void testProcessRequest() throws ServletException, IOException {
        when(request.getServletContext()).thenReturn(appContext);
        when(appContext.getRequestDispatcher(anyString())).thenReturn(rd);

        controller.doGet(request, response);
        verify(rd).forward(request, response);

        System.out.println("response.getStatus() = " + response.getStatus());
        assertEquals("text/html", response.getContentType());
    }
}

WelcomeController.java

@WebServlet(name = "WelcomeController", urlPatterns = {"/welcome.htm"})
public class WelcomeController extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        processRequest(request, response);
    }

    public void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("Into the WelcomeController...");
        RequestDispatcher rd = request.getServletContext().getRequestDispatcher("/jsp/welcome.jsp");
        rd.forward(request, response);
    }

}

Not sure why the response.getStatus() method would return 0 instead of 200 and >even the response.getContentType() is returning null.

因为 response 是一个 mock,当您调用 getStatus()getContentType()response 上的任何其他方法时,您将得到:

  • 编程行为 如果您使用 Mockito.when(...Mockito.doXXX(
  • 编程某些行为
  • 响应类型的默认值(int => 0String => null 等)

在你的例子中,response.getStatus() returns 一个 int 并且没有程序化的行为所以你得到 0response.getContentType() returns String 并且没有程序化的行为,所以你得到 null

project home page. See also the FAQ

上有一些文档值得一读