2016-11-23 15 views
1

mockitoユニットテストで例外のjson応答を取得したいと考えました。 これは私のアプリケーション構成ファイルです。タイプの戻り値に対してコンバーターが見つかりません:クラスjava.util.LinkedHashMap

@Configuration 
@EnableWebMvc 
@ComponentScan(basePackages = "com.spring") 
public class AppConfig extends WebMvcConfigurerAdapter{ 

    @Override 
    public void addResourceHandlers(ResourceHandlerRegistry registry) { 
     registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); 
    } 

} 

これは、既存のユーザーのための私の例外クラスです:

public class ConflictException extends RuntimeException{ 

    public ConflictException() { 

    } 

    public ConflictException(String message) { 
     super(message); 
    } 
} 

これは@ControllerAdviceで注釈を付け、私のグローバル例外コントローラクラスです。

@EnableWebMvc 
@ControllerAdvice 
public class GlobalExceptionHandlerController extends ResponseEntityExceptionHandler{ 

    public GlobalExceptionHandlerController() { 
     super(); 
    } 

    @ExceptionHandler(ConflictException.class) 
    public ResponseEntity<Map<String, Object>> handleException(
      Exception exception, HttpServletRequest request) { 
     ExceptionAttributes exceptionAttributes = new DefaultExceptionAttributes(); 
     Map<String, Object> responseBody = exceptionAttributes.getExceptionAttributes(exception, request, HttpStatus.CONFLICT); 
     return new ResponseEntity<Map<String,Object>>(responseBody, HttpStatus.CONFLICT); 
    } 
} 

さて、これは私のコントローラのテストクラスです:

@RunWith(SpringJUnit4ClassRunner.class) 
@WebAppConfiguration 
@EnableWebMvc 
@ActiveProfiles("Test") 
@ContextConfiguration(classes={AppConfig.class}) 
public class UserControllerTest { 

@InjectMocks 
    private UserController userController; 

    @Mock 
    private UserService service; 

private MockMvc mockMvc; 


    @Before 
    public void setup() { 
     MockitoAnnotations.initMocks(this); 

     final ExceptionHandlerExceptionResolver exceptionHandlerExceptionResolver = new ExceptionHandlerExceptionResolver(); 

      //here we need to setup a dummy application context that only registers the GlobalControllerExceptionHandler 
      final StaticApplicationContext applicationContext = new StaticApplicationContext(); 
      applicationContext.registerBeanDefinition("advice", new RootBeanDefinition(GlobalExceptionHandlerController.class, null, null)); 

      //set the application context of the resolver to the dummy application context we just created 
      exceptionHandlerExceptionResolver.setApplicationContext(applicationContext); 

      //needed in order to force the exception resolver to update it's internal caches 
      exceptionHandlerExceptionResolver.afterPropertiesSet(); 


     mockMvc = MockMvcBuilders.standaloneSetup(userController).setHandlerExceptionResolvers(exceptionHandlerExceptionResolver).build(); 

    } 

@Test 
    public void createUserExistsTest() throws Exception { 

     when(service.createUser(any(User.class))).thenThrow(new ConflictException("User exists.")); 

     mockMvc.perform(post("/user") 
       .content("{\"username\": \"bimal\", \"password\": \"check\", \"email\": \"[email protected]\", \"maxCaloriesPerDay\": \"1000\"}") 
       .contentType(MediaType.APPLICATION_JSON)) 
       .andDo(print()) 
       .andExpect(status().isConflict()); 
    } 
} 

私は私のテストメソッドを実行すると、私は次のエラーを取得:

ERROR:

org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver - Failed to invoke @ExceptionHandler method: public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> com.spring.app.exception.GlobalExceptionHandlerController.handleException(java.lang.Exception,javax.servlet.http.HttpServletRequest) 
java.lang.IllegalArgumentException: No converter found for return value of type: class java.util.LinkedHashMap 
    at org.springframework.util.Assert.isTrue(Assert.java:68) 

どのように缶を私はこのエラーを解決しますか?例外がスローされますが、変換して使用することはできません。

答えて

0

処理中です。このエラーは、応答エンティティタイプのHttpMessageConverterを参照していません。 JacksonHttpMessageConverterをspringコンテキストに追加します。あなたのAppConfigでWebMvcConfigurerAdapterから

オーバーライドこの方法:

@Override 
    public void configureMessageConverters(List<HttpMessageConverter> converters) { 
     messageConverters.add(new MappingJackson2HttpMessageConverter()); 
     super.configureMessageConverters(converters); 
    } 
+0

私はそれを追加しましたが、それでも私は「タイプの戻り値が見つかりませコンバータ:クラスjava.util.LinkedHashMap」になっていないのですエラーを。 LinkedHashMapを処理するためのMappingJackson2HttpMessageConverterのカスタマイズ方法 – bthapa

関連する問題