2017-12-08 9 views
0

私はSpringBoot Controllerのユニットテストをしようとしています。目標ヘッダーがAcceptを含む場合、application/json以外のものとして406 Not Acceptableを返すことをテストすることです。しかし、私はMockMvcで動作しないことがわかります。私は406の代わりに200 OKを取得しています。任意のアイデアをお願いします!もちろん、サービスは、私がPostmanまたは任意の残りのクライアントを使用してテストすると、期待通りに406を返します。問題テストSpring MockMvcのリクエストヘッダを受け入れる

@Test 
public void shouldRejectIfInvalidAcceptHeaderIsPassed() throws Exception { 

    HttpHeaders httpHeaders = new HttpHeaders(); 
    httpHeaders.add("Accept","application/xml"); 
    httpHeaders.add("Authorization", "some jwt token"); 

    this.mockMvc.perform(post("/sample/test") 
      .contentType(MediaType.APPLICATION_JSON) 
      .headers(httpHeaders) 
      .content(toJson(""))) 
      .andExpect(status().isNotAcceptable()); 

    // Then 
    verify(mockSampleService).getSampleOutput(); 
} 

そして、私のコントローラ

@RestController 
@Validated 
@RequestMapping(PATH_PREFIX) 
public class SampleController { 

    public static final String PATH_PREFIX = “/sample”; 

    private final SampleService sampleService; 

    @Autowired 
    public SampleController(SampleService sampleService) { 
     sampleService = sampleService; 
    } 


    @RequestMapping(value = “/test”, method = RequestMethod.POST)) 
    public SampleResponse createSession() { 
     return sampleService.getSampleOutput(); 
    } 

} 
+0

コントローラの外観はどうですか? – pvpkiran

+0

今質問のコントローラを見つけてください。 – deejo

答えて

0

ああ、のように見えます!私は問題を特定し、修正しました。コントローラーには、@RequestMapping(headers="Accept=application/json")が必要です。そうでなければMockMvcは期待されるフォーマットを識別できません。

関連する問題