Slice-based testing

Across the industry, many express an interest in testing. Yet, when push comes to shove and we run into tricky situations, it's quite easy to throw up our hands and shout, This is too hard!

Spring Boot aims to help!

JUnit, all by itself, gives us the power to declare tests and assert pass/fail scenarios. But in reality, not everything works straight out of the box. For example, parts of our code will easily come to rely upon Boot autoconfiguring various beans as well as having that powerful property support.

A keen example is the need to do some MongoDB operations. It would be quite handy if we could ask Spring Boot to autoconfigure just enough beans to support MongoDB for our tests but nothing else.

Well, today's our lucky day.

Spring Boot 1.5 introduced slice testing. This is where a subset of Spring Boot's autoconfiguration power can be switched on, while also having full access to its property support. The following list of test annotations each enable a different slice of code:

  • @DataMongoTest
  • @DataJpaTest
  • @JdbcTest
  • @JsonTest
  • @RestClientTest
  • @WebFluxTest
  • @WebMvcTest

Each of these annotations enables a different slice of beans to be configured. For example, @DataJpaTest will:

  • Enable transactions by applying Spring's @Transactional annotation to the test class
  • Enable caching on the test class, defaulting to a NoOp cache instance
  • Autoconfigure an embedded test database in place of a real one
  • Create a TestEntityManager bean and add it to the application context
  • Disable the general Spring Boot autoconfiguration, confining things to the autoconfiguration policies found in spring-boot-test-autoconfigure
All of these annotations require additionally annotating our test class with @RunWith(SpringRunner.class).

An important point to understand is that tests work best when confined to a relatively narrow scope. Hence, using more than one of these @...​Test annotations is not recommended. Instead, break things up into multiple test classes.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.220.152.139