2017-07-19 21 views
0

私は@MockBean依存関係で、春ブートアプリケーションのHandlerInterceptorをテストするための右のコンフィギュレーションを見つけようとしているのテスト時(@PostContructコントローラコールの後に@Beforeコールが来ることを知っている)避けコントローラの初期化、が、全体Beanプールを初期化せずに春のブートHandlerInterceptor

今のところ、私はこの構文になってきた:

@RunWith(SpringJUnit4ClassRunner.class) 
@SpringBootTest(classes = Application.class) 
public class MyHandlerInterceptorTest { 
    @Autowired 
    private RequestMappingHandlerAdapter handlerAdapter; 
    @Autowired 
    private RequestMappingHandlerMapping handlerMapping; 
    @MockBean 
    private ProprieteService proprieteService; 
    @MockBean 
    private AuthentificationToken authentificationToken; 

    @Before 
    public void initMocks(){ 
    given(proprieteService.methodMock(anyString())).willReturn("foo"); 
    } 

    @Test 
    public void testInterceptorOptionRequest() throws Exception { 
    MockHttpServletRequest request = new MockHttpServletRequest(); 
    request.setRequestURI("/some/path"); 
    request.setMethod("OPTIONS"); 

    MockHttpServletResponse response = processPreHandleInterceptors(request); 
    assertEquals(HttpStatus.OK.value(), response.getStatus()); 
    } 
} 

しかし、テストが失敗し、は@PostContructコールを持つので、この時点で嘲笑されていないproprieteServiceモックからデータを取得しようとします。

私の質問は次のとおりです。Springbootテストローダーがどのように私のコントローラを初期化するのを防ぐことができますか?1:私はテストの必要はありません。

+3

ユニットテストを作成する統合テストではありません。 'HandlerInterceptor'をインスタンス化し、モックを作成して注入します。 –

+0

その場合、インターセプタに '@ autowired'依存関係をモックする方法はありますか?特別なスプリングブートの注釈が必要になります。@ SpringBootTestがその仕事をしていました。 – Aphax

答えて

1

@M。 Deinumは私に道を教えてくれました。確かに実際のUnitテストを書くことが解決策でした。私の心配は、私がIntercepterにそれらの@autowiredの依存関係を設定する必要があり、いくつかの魔法の注釈を探していたということでした。

@Configuration 
public class CustomWebMvcConfigurerAdapter extends WebMvcConfigurerAdapter { 
    AuthentificationToken authentificationToken; 

    @Autowired 
    public CustomWebMvcConfigurerAdapter(AuthentificationToken authentificationToken) { 
    this.authentificationToken = authentificationToken; 
    } 

    @Bean 
    public CustomHandlerInterceptor customHandlerInterceptor() { 
    return new CustomHandlerInterceptor(authentificationToken); 
    } 

    @Override 
    public void addInterceptors(InterceptorRegistry registry) { 
    registry.addInterceptor(customHandlerInterceptor()); 
    } 
} 

そしてインターセプタ:これは助けることができる

public class CustomHandlerInterceptor implements HandlerInterceptor { 
    private AuthentificationToken authentificationToken; 

    @Autowired 
    public CustomHandlerInterceptor(AuthentificationToken authentificationToken) { 
    this.authentificationToken = authentificationToken; 
    } 

    @Override 
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { 
    } 
} 

願っていますが、それだけでカスタムWebMvcConfigurerAdapterを編集して、このようなコンストラクタを介して依存関係を渡すために簡単でした。

関連する問題