Я добавил валидацию к классам в приложении, которое предоставляет 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());
*Контроллер 1007 *:
@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>
Application.java
@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 = []