(forked and converted to kotlin)
This small repository provides some example Spring Boot Tests verifying the correct implementation of a very simple RestController
.
(If you are new to this topic, you can start with this "Building a RESTful Web Service" tutorial.)
The tests can be done with a manually wired MockMvc
client or with a with a manually wired WebTestClient
client.
If the class creation is under the control of Spring, the MockMvc
client will by automatically wired and then can be run against a mocked servlet or an embedded server.
Similar, WebTestClient
client will by automatically wired and then can be run against a mocked servlet or an embedded server. (Both approaches are described here (mock environment) and here (running server).)
However, the straight-forward solution to test by MockMvc
is to run a WebMvcTest
.
Correspondingly, the straight-forward solution to test by WebTestClient
is to run a WebFluxTest
.
In order to see all the tests succeeding, just check out and run mvn test
.
- Note #1: Thanks to JUnit5's Extension Model, the
RunWith
annotation is not required anymore. - Note #2: Since JUnit5 supports n-ary test methods, the
Autowired
clients might be provided as a test method parameter or (not shown in the code) might be declared as test class fields. (Also annotated withAutowired
.) - Note #3: This simple Maven project specifies a MVC controller but additionally uses WebFlux for testing.
Spring explicitly allows both modules to be used simultaneously – but one is preferred over the other.
Thus, if the WebTestClient requires a WebFlux Context, the
spring.main.web-application-type
must be specified accordingly.