当前位置: 首页 > 知识库问答 >
问题:

MockMVC在SpringTest中返回404和pageNotFound警告

万俟穆冉
2023-03-14

我在过去一周一直在研究,无法找到解释为什么我在springMVC中的测试用例会抛出404。它会记录未找到页面的警告。我非常确定我的配置是正确的,并且应用程序上下文已加载。为什么mockMvc不执行请求并返回200状态等。?

这是我的测试课:

    package com.fdmgroup.issuetracker.controller;

import static org.junit.Assert.*;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MockMvcBuilder;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestContext;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

import com.fdmgroup.issuetracker.model.impl.User;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.*;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:*/test-context.xml")
@WebAppConfiguration
public class LoginControllerTest {
    @Autowired
    private WebApplicationContext wac;

    private MockMvc mockMvc;
    private User user;
    @Before
    public void setUp() throws Exception {


        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();

    }

    @After
    public void tearDown() throws Exception {
    }

    @Test
    public void testIfDisplayLoginPageReturnsLoginJsp() throws Exception {
    mockMvc.perform(get("/login")).andExpect(status().isOk());
    }

    @Test
    public void testLoginServlet() throws Exception {
    String username = "Corey";
    String password = "Password";

        mockMvc.perform(post("/LoginServlet").param("username", username).param("password", password)).andExpect(status().isOk());
    }

}

跟踪以及控制台日志:

java.lang.AssertionError: Status expected:<200> but was:<404>
    at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:60)
    at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:89)
    at org.springframework.test.web.servlet.result.StatusResultMatchers$10.match(StatusResultMatchers.java:655)
    at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:171)
    at com.fdmgroup.issuetracker.controller.LoginControllerTest.testIfDisplayLoginPageReturnsLoginJsp(LoginControllerTest.java:48)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:254)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    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:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:193)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)



12:26:59  INFO [main] - org.springframework.test.context.web.WebTestContextBootstrapper.getDefaultTestExecutionListenerClassNames - Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]
12:26:59  INFO [main] - org.springframework.test.context.web.WebTestContextBootstrapper.instantiateListeners - Could not instantiate TestExecutionListener [org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]. Specify custom listener classes or make the default listener classes (and their required dependencies) available. Offending class: [org/springframework/transaction/interceptor/TransactionAttribute]
12:26:59  INFO [main] - org.springframework.test.context.web.WebTestContextBootstrapper.instantiateListeners - Could not instantiate TestExecutionListener [org.springframework.test.context.transaction.TransactionalTestExecutionListener]. Specify custom listener classes or make the default listener classes (and their required dependencies) available. Offending class: [org/springframework/transaction/interceptor/TransactionAttributeSource]
12:26:59  INFO [main] - org.springframework.test.context.web.WebTestContextBootstrapper.getTestExecutionListeners - Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener@5afa04c, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@6ea12c19, org.springframework.test.context.support.DependencyInjectionTestExecutionListener@6a024a67, org.springframework.test.context.support.DirtiesContextTestExecutionListener@7921b0a2]
12:27:00  INFO [main] - org.springframework.web.context.support.GenericWebApplicationContext.prepareRefresh - Refreshing org.springframework.web.context.support.GenericWebApplicationContext@6a41eaa2: startup date [Thu Jan 11 12:27:00 EST 2018]; root of context hierarchy
12:27:00  INFO [main] - org.springframework.mock.web.MockServletContext.log - Initializing Spring FrameworkServlet ''
12:27:00  INFO [main] - org.springframework.test.web.servlet.TestDispatcherServlet.initServletBean - FrameworkServlet '': initialization started
12:27:00  INFO [main] - org.springframework.test.web.servlet.TestDispatcherServlet.initServletBean - FrameworkServlet '': initialization completed in 162 ms
12:27:00  WARN [main] - org.springframework.web.servlet.PageNotFound.noHandlerFound - No mapping found for HTTP request with URI [/login] in DispatcherServlet with name ''
12:27:00  INFO [Thread-0] - org.springframework.web.context.support.GenericWebApplicationContext.doClose - Closing org.springframework.web.context.support.GenericWebApplicationContext@6a41eaa2: startup date [Thu Jan 11 12:27:00 EST 2018]; root of context hierarchy

最后是我的背景。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:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.1.xsd
    http://www.springframework.org/schema/aop 
    http://www.springframework.org/schema/aop/spring-aop-3.2.xsd">

    <aop:aspectj-autoproxy proxy-target-class="true" />
    <context:annotation-config/>

    <context:component-scan base-package="com.fdmgroup.issuetracker" />
    <bean id="UserDAO" class="com.fdmgroup.issuetracker.model.impl.UserDAO"></bean>
    <bean id="IssueDAO" class="com.fdmgroup.issuetracker.model.impl.IssueDAO"></bean>
    <bean id="newUser" class="com.fdmgroup.issuetracker.model.impl.User"
        scope="prototype"></bean>
    <bean id="newIssue" class="com.fdmgroup.issuetracker.model.impl.Issue"
        scope="prototype"></bean>
    <bean id="newRole" class="com.fdmgroup.issuetracker.model.impl.Role" scope="prototype"></bean>
    <bean id="newDept" class="com.fdmgroup.issuetracker.model.impl.Department" scope="prototype"></bean>
    <bean id="newIssueUpdate" class="com.fdmgroup.issuetracker.model.impl.IssueUpdate" scope="prototype"></bean>
</beans>

如果还需要什么来分析这个问题,请告诉我。

共有2个答案

海翔宇
2023-03-14

答案在您包含的堆栈跟踪中

12:27:00  WARN [main] - org.springframework.web.servlet.PageNotFound.noHandlerFound - No mapping found for HTTP request with URI [/login] in DispatcherServlet with name ''

因此,您没有注册一个控制器来处理/login请求路径。

您需要包含Spring MVC的XML配置文件才能使测试正常工作。

毛博
2023-03-14

尝试在测试类上方添加此注释

@ContextConfiguration(classes = <YourController>.class)
public class ControllerTest {
 类似资料:
  • 我编写了controller,它为每个映射使用了不同的值。现在我将它简化为对所有映射使用相同的值,但是我不知道如何使test工作,因为它在每个映射上都返回404。 这里是我的控制器: 和我的测试: 404及以下所有测试结果: 在org.springframework.test.util.assertionerrors.fail(assertionerrors.java:59)在org.spring

  • Spring靴1.5.9及以下版本: 我一直得到:WARNo.s.web.servlet.PageNotFind-没有找到HTTP请求与URI[api/v1/app/pool]在DispatcherServlet与名称的映射”

  • LoginController.java spring-config-servlet.xml http://www.springframework.org/schema/jdbc/springframework.org/schema/mvc/springmvc-4.3.xsd http://www.springframework.org/schema/mvc/springmvc-4.3.xsd h

  • 我正在尝试为我的Spring项目运行集成测试,它是一个简单的get方法,用于从DB返回给定id的字符串输出。但是在Mockmvc中,我一直在Mockmvc上得到一个NullPointerException。在我的测试范围内执行。 以下是测试: 这里是控制器-输出控制器: 完全错误是:

  • 我是新来的Laravel使用本地开发环境与家园尝试运行简单的测试 路由/网络。php: 运行phpunit返回404错误 vagrant@homestead:~/code/laravel$phpunit phpunit 6.4。3由塞巴斯蒂安·伯格曼和撰稿人撰写。 .F.3/3(100%) 时间:1.07秒,内存:10.00MB 有1次失败: 1) Tests\Feature\UserTest::

  • 我正在开发SpringCloudStream的Brooklyn.Release版本。我的用例具有多个接收器的HttpSource。当我将初学者应用程序依赖项添加到应用程序中并使用它时,如下所示: 我的聚合应用程序是 一直得到如下响应: