2017-06-13 4 views
1

私はSpringBoot 2とSpring 5(RC1)を使ってリアクティブなRESTサービスを公開しています。私はそれらのコントローラの単体テストを書くことはできません。ここでテストスプリング5リアクティブレストサービス

私は本当のものを呼び出すためにないたいと思いますので、私のコントローラ

@Api 
@RestController 
@RequestMapping("/") 
public class MyController { 

    @Autowired 
    private MyService myService; 


    @RequestMapping(path = "/", method = RequestMethod.GET) 
    public Flux<MyModel> getPages(@RequestParam(value = "id", required = false) String id, 
      @RequestParam(value = "name", required = false) String name) throws Exception { 

     return myService.getMyModels(id, name); 
    } 
} 

myServiceというデータベースを呼び出していますさ。 (私は統合テストをwan'tはありません)

編集:

私は私の必要性を一致させることができますが、私はそれを動作させることができない方法が見つかりました:

@Before 
    public void setup() { 

     client = WebTestClient.bindToController(MyController.class).build(); 

    } 
@Test 
    public void getPages() throws Exception { 

     client.get().uri("/").exchange().expectStatus().isOk(); 

    } 

をしかし、私はよ404を取得するとコントローラが見つかりません

+0

クイックGoogleショット:http://memorynotfound.com/unit-test-spring-mvc-rest-service-junit-mockito/ – jannis

+1

こんにちは@jannis、ありがとうございますが、それは残りのAPIテストでも、反応性の残りのAPIテストでもありません私はもちろん、この1つのグーグルで開始しました – Seb

+0

申し訳ありませんが、Fluxの部分に気付かなかった... – jannis

答えて

3

bindToControllerメソッドに実際のコントローラインスタンスを渡す必要があります。 モック環境をテストしたいので、例えばMockitoを使って依存関係をモックする必要があります。

public class MyControllerReactiveTest { 

    private WebTestClient client; 

    @Before 
    public void setup() { 
     client = WebTestClient 
       .bindToController(new MyController(new MyService())) 
       .build(); 
    } 

    @Test 
    public void getPages() throws Exception { 
     client.get() 
       .uri("/") 
       .exchange() 
       .expectStatus().isOk(); 
    } 

} 

hereより多くのテスト例があります。

また、constructor-based DIに切り替えることをお勧めします。

+0

はうまく動作します!どうもありがとう – Seb