2017-02-16 39 views
1

這是我的控制器......java.lang.AssertionError:狀態預計:<200>卻被:<400>春季球衣控制器

@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:狀態預計:< 200>卻被:< 400>」

+0

您確定'infoService'被注入到您的控制器中嗎?在我看來,你必須調用'MockMvcBuilders.standaloneSetup'然後'MockitoAnnotations.initMocks' –

回答

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()) 
     ...