【问题标题】:java.lang.AssertionError: Status expected:<200> but was:<400> in spring jersey controllerjava.lang.AssertionError: Status expected:<200> but was:<400> in spring jersey controller
【发布时间】:2017-02-16 12:13:06
【问题描述】:

这是我的控制器...

@GET
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    @Path("/categories")
    public POSResponse getAllCategories() {
        String countryCode="1";
        return infoService.getAllCategories(countryCode);
    }

这是我的 testController....

  @Mock
    InfoService infoService;
    @InjectMocks
    private InfoController infoController;

    private MockMvc mockMvc;
    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
        mockMvc = MockMvcBuilders.standaloneSetup(infoController).build();
    }

    @Test
    public void getAllCategoriesTest() throws Exception {
        POSResponse response=new POSResponse();
        Category category=new Category();
        category.setCountryCode(1);
        category.setDescription("Mother Dairy");
        response.setResponse(category);

        when(infoService.getAllCategories("1")).thenReturn(response);

        mockMvc.perform(get("/categories"))
                .andExpect(status().isOk())
                .andExpect(content().contentType(APPLICATION_JSON_UTF8))
                .andExpect(jsonPath("$.id", is(1)))
                .andExpect(jsonPath("$.description", is("Mother Dairy")));

        verify(infoService, times(1)).getAllCategories("1");
        verifyNoMoreInteractions(infoService);
    }

我正在使用球衣控制器。 当我调用该方法时,我收到错误消息“java.lang.AssertionError: Status expected: but was:”

【问题讨论】:

  • 你确定infoService 被注入你的控制器了吗?在我看来,您必须先致电 MockMvcBuilders.standaloneSetup,然后再致电 MockitoAnnotations.initMocks

标签: spring junit mockito


【解决方案1】:

你是否可以在你的控制器中使用:

@Consumes(MediaType.APPLICATION_JSON) // instead of MediaType.APPLICATION_FORM_URLENCODED

或者,在你的测试中:

mockMvc.perform(get("/categories")
       .contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE))
       ...

为什么?

HTTP 请求应该是服务器接受的媒体类型之一,MockMvc 可能使用MediaType.APPLICATION_JSON(如我的测试所示!)。您可以通过打印请求详细信息来检查它:

mockMvc.perform(get("/categories")
       .contentType(MediaType.APPLICATION_FORM_URLENCODED))
       .andDo(MockMvcResultHandlers.print())
       ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-15
    • 2022-01-23
    • 1970-01-01
    相关资源
    最近更新 更多