SpringBoot unit test example: basic unit testing
Now is the springboot world, so ,if you want to do unit test with spring boot, here is a tutorial, Let’s begin.
Since spring boot 1.5.9, spring has simplifed the unit test framework, it’s very easy to test springbeans now.
1. Pom.xml
Here we use spring boot 1.5.9
2. Define on spring bean for test
Here we define a spring bean named DemoService for demo,which is a @Service bean contains a addCount method ,here is the code.
Then we got this directory structure:
3. Now define the TestCase to test addCount method
Now it’s the trick:
the explain:
- @Runwith would tell the underground junit framework to run this test with spring runner
- @SpringBootTest would let this testcase setup the springboot env.
- @Autowired would inject the service bean we want to test
- @Test is the junit annotation
- assertThat is the assertJ static method to do assertions, it’s very concise and readable.
4. Now run the test
we got the result as follows:
You can find detail documents about the springboot and unit testing here:
The example code can be found here: