【问题标题】:java.lang.AssertionError: Status expected:<200> but was:<404>java.lang.AssertionError:预期状态:<200> 但原为:<404>
【发布时间】:2017-01-20 15:36:35
【问题描述】:

我知道这个问题有很多类似的帖子。我试图实现所有但不为我工作。请帮助我为什么会收到此错误 java.lang.AssertionError: Status expected: but was:

我尝试实现 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 信息: 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>

在 region-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>

【问题讨论】:

  • 那么这个语句“resultActions.andExpect(status().isOk())”是如何产生true的。Bzc isOk() 将断言响应状态是{@code HttpStatus.OK} (200)。
  • 你在xml中有这个吗? &lt;mvc:annotation-driven&gt;&lt;/mvc:annotation-driven&gt;。与我们分享您的配置 XML,因为它可能是 spring 配置问题,或者可能只是模拟 mvc 的错误构建。
  • 您能否公开一个没有任何响应的简单 get 方法并通过您的测试用例断言响应状态并让我们知道结果。 Bzc 我看到你所有的配置都是正确的,对请求映射有疑问。
  • 分享了 xml 信息
  • @Sunil,好的,我也会检查 Get Method

标签: java unit-testing spring-mvc mockito


【解决方案1】:

即使您启用了 WebMvc,您也需要扫描您的控制器以自动注册控制器和 url 映射。组件扫描扫描包以在应用程序上下文中查找和注册 bean。

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

我怀疑您的上下文 xml 中缺少组件扫描。如果是这样,请在您的 beanRefContext.xml 中添加此语句。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-25
    • 2019-02-26
    • 2021-08-05
    • 1970-01-01
    • 2022-01-17
    相关资源
    最近更新 更多