Reputation: 3902
I'm using SpringBoot 2 and Spring 5 (RC1) to expose reactive REST services. but I can't manage to write unit test for those controllers.
Here is my controller
@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 is calling a database so I would like not to call the real one. (I don't wan't integration testing)
Edit :
I found a way that could match my need but I can't make it work :
@Before
public void setup() {
client = WebTestClient.bindToController(MyController.class).build();
}
@Test
public void getPages() throws Exception {
client.get().uri("/").exchange().expectStatus().isOk();
}
But I'm getting 404, seems it can't find my controller
Upvotes: 1
Views: 1350
Reputation: 2382
You have to pass actual controller instance to bindToController
method.
As you want to test mock environment, you'll need to mock your dependencies, for example using 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();
}
}
More test examples you can find here.
Also, I suggest switching to constructor-based DI.
Upvotes: 4