测试 spring 5 反应性休息服务
test spring 5 reactive rest service
我正在使用 SpringBoot 2 和 Spring5 (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,似乎找不到我的控制器
您必须将实际控制器实例传递给 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。
我正在使用 SpringBoot 2 和 Spring5 (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,似乎找不到我的控制器
您必须将实际控制器实例传递给 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。