2016-09-13 2 views
1

Я знаю, что существует так много подобных сообщений для этого вопроса. Я пытался реализовать все, но не работал для меня. Пожалуйста, помогите мне, почему я получаю эту ошибку java.lang.AssertionError: Статус ожидается: < 200> но: < 404>java.lang.AssertionError: Ожидаемый статус: <200> но был: <404>

Я пытался реализовать MediaType.APPLICATION_JSON аннотаций @EnableWebMvc Но не работает

Нужно ли включать заголовки, чтобы они работали? Пожалуйста, дайте мне знать,

код, который я написал это: класс

Контроллер:

@EnableWebMvc 
@Controller 
public class Controller { 

@RequestMapping(value = "/app/data", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE) 
    public ResponseEntity<ResponseData> DataInquiry(
      @RequestBody RequestData requestData, 
      @RequestHeader(value = Constants.ID, required = false) String transactionId) { 
     //Do some action 
     return new ResponseEntity<ResponseData>(responseData, headers, HttpStatus.OK); 
} 

ControllerTest класс:

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration({"classpath*:spring/beanRefContext.xml"}) 
@WebAppConfiguration 
public class ControllerTest{ 

    public static final MediaType APPLICATION_JSON_UTF8 = new MediaType(MediaType.APPLICATION_JSON.getType(), 
      MediaType.APPLICATION_JSON.getSubtype(), 
      Charset.forName("utf8")); 

private MockMvc mockMvc; 

    @Autowired 
    WebApplicationContext wac; 

ObjectMapper mapper; 
    AnnotationMethodHandlerAdapter adapter; 
    MockHttpServletRequest request; 
    MockHttpServletResponse response; 

@Before 
    public void setUp() { 
     System.out.println("Before method execution in CommonInquiryControllerTest class "); 
     //this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); 
     MockitoAnnotations.initMocks(this); 
     this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).dispatchOptions(true).build(); 

     adapter = new AnnotationMethodHandlerAdapter(); 
     request = new MockHttpServletRequest(); 
     response = new MockHttpServletResponse(); 
     mapper = new ObjectMapper(); 
    } 

@Test 
    public void InquiryDataTest() throws Exception, JsonProcessingException 
    { 
     RequestData anObject = new RequestData(); 

     anObject.setId("1234"); 
     anObject.setQualifier("someData");  

     mapper = new ObjectMapper(); 
     mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false); 
     ObjectWriter ow = mapper.writer().withDefaultPrettyPrinter(); 
     String requestJson=ow.writeValueAsString(anObject); 

     assertNotNull(anObject.getId()); 
     assertNotNull(anObject.getQualifier()); 

     ResultActions resultActions = mockMvc 
       .perform(post("/app/data") 
       .contentType(MediaType.APPLICATION_JSON) 
       .accept(MediaType.APPLICATION_JSON) 
       .content(mapper.writeValueAsBytes(requestJson))); 

      resultActions.andExpect(status().isOk()); 

      //This will print the response JSON string 
      resultActions.andDo(MockMvcResultHandlers.print()); 

     Assert.assertEquals(200, response.getStatus()); 
} 

XML Info: beanContext.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:jee="http://www.springframework.org/schema/jee" 
    xmlns:tx="http://www.springframework.org/schema/tx" 
    xmlns:task="http://www.springframework.org/schema/task" 
    xmlns:mvc="http://www.springframework.org/schema/mvc" 
    xmlns:context="http://www.springframework.org/schema/context" 
    xmlns:encryption="http://www.jasypt.org/schema/encryption" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans.xsd 
    http://www.springframework.org/schema/jee 
    http://www.springframework.org/schema/jee/spring-jee.xsd 
    http://www.springframework.org/schema/tx 
    http://www.springframework.org/schema/tx/spring-tx.xsd 
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context.xsd 
    http://www.jasypt.org/schema/encryption 
    http://www.jasypt.org/schema/encryption/jasypt-spring3-encryption-1.xsd 
    http://www.springframework.org/schema/task 
    http://www.springframework.org/schema/task/spring-task-4.0.xsd 
    http://www.springframework.org/schema/mvc 
    http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd"> 

    <import resource="classpath:core-application-context.xml"/> 
    <import resource="classpath:region-context.xml"/> 

    <jee:jndi-lookup id="somedataSourceid" jndi-name="some name" proxy-interface="javax.sql.DataSource"/> 

    <!-- enable the configuration of transactional behavior based on annotations --> 
    <tx:annotation-driven/> 
    <bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/> 
    <!-- a PlatformTransactionManager is still required --> 
    <bean id="transactionManager" class="org.springframework.transaction.jta.WebSphereUowTransactionManager"/> 

</beans> 

В регионе-context.xml:

<?xml version="1.0" encoding="UTF-8"?> 
<beans default-lazy-init="true" xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jee="http://www.springframework.org/schema/jee" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd 
    http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd"> 

    <!-- Import this context file and pass it the requisite properties and a Data Source named dataSource --> 
    <context:component-scan base-package="com.java.geek"/> 
</beans> 
+0

Затем, как это утверждение «resultActions.andExpect (status(). IsOk())» приведено true.Bzc isOk() будет утверждать, что статус ответа {@code HttpStatus.OK} (200). –

+0

У вас есть это в xml? ''. Поделитесь с нами своим конфигурационным XML, потому что это может быть проблема конфигурации весны или, может быть, просто неправильное построение mockc mooc. – Hrabosch

+0

Можете ли вы представить простой метод get без ответа и утвердить статус ответа, хотя ваш тестовый пример и сообщить нам результат. Bzc Я вижу, что вся ваша конфигурация верна, сомневаюсь в сопоставлении запросов. –

ответ

0

Даже если вы Enable WebMvc, вы должны проверить ваш контроллер для управления авто регистра & URL mappings.component-сканирования сканирует пакеты, чтобы найти и зарегистрировать бобы в контексте приложения ,

<context:component-scan base-package="com.mycompany.xyz" /> 

Я сомневаюсь, что сканирующий компонент отсутствует в вашем контексте xml.If так Добавить это заявление в вашем beanRefContext.xml.

+0

Это уже есть в xml. – AIM

Смежные вопросы