试验弹簧5反应性休息服务

时间:2017-06-13 19:19:03

标签: spring rest spring-boot reactor

我使用SpringBoot 2和Spring 5(RC1)来公开反应式REST服务。但我无法为这些控制器编写单元测试。

这是我的控制器

@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正在调用数据库,所以我不想调用真正的数据库。 (我不想进行集成测试)

编辑:

我找到了一种方法可以满足我的需求,但我无法使其发挥作用:

@Before
    public void setup() {

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

    }
@Test
    public void getPages() throws Exception {

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

    }

但是我得到了404,似乎无法找到我的控制器

1 个答案:

答案 0 :(得分: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