有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Spring MockMvc未找到处理程序方法

我已经在一个提供REST API的应用程序中为类添加了验证,我正在尝试重新构造单元测试以使用MockMvc,以便调用验证。我已经看过几个关于设置这个的教程,但每当我尝试调用其中一个API时,就会得到一个404空响应,日志文件显示“没有找到/xxxxx的处理程序方法”

在XML配置文件或测试类中,我可能只是缺少了一些东西,但我一直没有弄清楚

测试代码:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring_test.xml")
@TestPropertySource("classpath:test.properties")
@WebAppConfiguration
public class ClientControllerTest {
    @Autowired
    private Validator validator;

    private MockMvc mockMvc;

    @Autowired
    private WebApplicationContext webApplicationContext;

    private static final String baseUrl = "http://localhost:8080";

    @Mock
    StorageProvider       storageProvider;

    @Mock
    ClientCriteria        clientCriteria;

    @Mock
    UserPermissionChecker userPermissionChecker;

    @Before
    public void setUp() throws BusinessException {
        MockitoAnnotations.initMocks(this);
        String identityUserToken = "TEST USER";
        Mockito.when(userPermissionChecker.checkPermissions(Mockito.any())).thenReturn(identityUserToken);

        mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
    }

    @Test
    public void testMockMvc() throws Exception {
        String clientId = "1";
        String channel = "internet";
        String market = "canada";
        String transactionStyle = "blah";
        String featureSet = "blah_blah";

        Client requestedClient = new Client(clientId, channel, market, transactionStyle, featureSet);

        ServletContext sc = webApplicationContext.getServletContext();
        assertNotNull(sc);
        assertTrue(sc instanceof MockServletContext);

        ResultActions ra = mockMvc.perform(post("/myapibase/v1/clients")
                        .contentType(MediaType.APPLICATION_JSON)
                        .content(TestUtil.convertObjectToJsonBytes(requestedClient))
        );

        ra.andDo(print());

控制器:

@RestController
@RequestMapping("/myapibase/v1")
public class ClientController {

    @Autowired
    private Validator validator;

    @Autowired
    private StorageProvider       storageProvider;

    @Autowired
    private UserPermissionChecker userPermissionChecker;

    private String                baseUrl;

    private static Logger         log                          = LoggerFactory.getLogger(ClientController.class.getName());

    @Autowired
    public ClientController(String baseUrl) {
        this.baseUrl = baseUrl;
    }

    @RequestMapping(value = "/clients", method = RequestMethod.POST)
    public ResponseEntity<?> addClient(@RequestBody @Valid Client clientToAdd, @RequestHeader HttpHeaders headers, @RequestParam Map<String, String> queryParams) {
        String methodName = "addClient";

    ...
    }

XML配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:security="http://www.springframework.org/schema/security"
       xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
                http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
                http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
                http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <context:annotation-config />
    <tx:annotation-driven/>
    <mvc:annotation-driven/>
    <!--<mvc:default-servlet-handler/>-->

    <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />

    <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basenames">
            <list>
                <value>classpath:ValidationMessages</value>
            </list>
        </property>
        <property name="defaultEncoding" value="UTF-8"/>
    </bean>

    <bean id="messageAccessor" class="org.springframework.context.support.MessageSourceAccessor">
        <constructor-arg index="0" ref="messageSource"/>
    </bean>

</beans>

申请。爪哇

@Configuration
@EnableAutoConfiguration(exclude = MetricRepositoryAutoConfiguration.class)
@EnableAspectJAutoProxy(proxyTargetClass = true)
@EnableServiceFoundation
@ComponentScan(basePackages = { "com.myapp.controllers", "com.myapp.models", "com.myapp.storage", "com.myapp.managers",
        "com.myapp.txyz", "com.myapp.util", })
public class Application {

    ...
}

日志输出:

22:04:30.866 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating instance of bean 'org.springframework.web.servlet.support.SessionFlashMapManager'
22:04:30.870 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.transaction.config.internalTransactionAdvisor'
22:04:30.871 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Finished creating instance of bean 'org.springframework.web.servlet.support.SessionFlashMapManager'
22:04:30.871 [main] DEBUG o.s.t.w.s.TestDispatcherServlet - Unable to locate FlashMapManager with name 'flashMapManager': using default [org.springframework.web.servlet.support.SessionFlashMapManager@1f7076bc]
22:04:30.871 [main] DEBUG o.s.t.w.s.TestDispatcherServlet - Published WebApplicationContext of servlet '' as ServletContext attribute with name [org.springframework.web.servlet.FrameworkServlet.CONTEXT.]
22:04:30.871 [main] INFO  o.s.t.w.s.TestDispatcherServlet - FrameworkServlet '': initialization completed in 38 ms
22:04:30.872 [main] DEBUG o.s.t.w.s.TestDispatcherServlet - Servlet '' configured successfully
22:04:30.978 [main] DEBUG o.s.t.w.s.TestDispatcherServlet - DispatcherServlet with name '' processing POST request for [/myapibase/v1/clients]
22:04:30.981 [main] DEBUG o.s.w.s.m.m.a.RequestMappingHandlerMapping - Looking up handler method for path /myapibase/v1/clients
22:04:30.982 [main] DEBUG o.s.w.s.m.m.a.RequestMappingHandlerMapping - Did not find handler method for [/myapibase/v1/clients]
22:04:30.982 [main] WARN  o.s.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/myapibase/v1/clients] in DispatcherServlet with name ''
22:04:30.983 [main] DEBUG o.s.t.w.s.TestDispatcherServlet - Successfully completed request

MockHttpServletRequest:
         HTTP Method = POST
         Request URI = /myapibase/v1/clients
          Parameters = {}
             Headers = {Content-Type=[application/json]}

             Handler:
                Type = null

               Async:
       Async started = false
        Async result = null

  Resolved Exception:
                Type = null

        ModelAndView:
           View name = null
                View = null
               Model = null

            FlashMap:

MockHttpServletResponse:
              Status = 404
       Error message = null
             Headers = {}
        Content type = null
                Body = 
       Forwarded URL = null
      Redirected URL = null
             Cookies = []

共 (0) 个答案