2017-06-13 79 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

快速谷歌拍攝:http://memorynotfound.com/unit-test-spring-mvc-rest-service-junit-mockito/ – jannis

+1

嗨@jannis,謝謝,但它既不休息API測試也無反應休息API測試當然我也開始用google搜索這個 – 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