Integrating Testing with Spring framework

This post is the first in the three posts series of testing in Java, and what we have done while we developed the MyCollab product. The content of these three parts are:

  • Part 1: Unit test with Spring framework (This post)
  • Part 2: Database Testing with DbUnit
  • Part 3: Mock testing with Mockito in the real examples of testing scheduler job and email sender

I have the knowledge graph links among these parts. Let us start with the first part, set up the new testing environment in the Spring project

Adding the Maven dependencies

You must add Junit, Spring-test to your project.

Write your first empty test case

This test case does nothing; you run it, and your IDE will show the green bar if you configure the testing project property. SpringJUnit4ClassRunner is the custom extension of Spring let JUnit can execute the test case under the Spring context. The annotation ContextConfiguration is the metaclass level; which defines how to load and configures application context in your integration test. In this example, I assume to use the annotation Spring configuration class to set up all Spring components. The initial configuration of this class is

If you have used Spring framework before, the configuration class ask Spring framework scan all classes in the package “com.example.**.service” to find the Spring components, but what is the meaning of the annotation Profile and its value testing. The reason to use Profile to segregate parts of configuration because when you use the annotation scanner in the integration testing, your classpaths may have several Spring components which are only presented in the production only, and their presence may corrupt the testing process, or simply they are not helpful. There are some examples of using the Spring profile

  • Your data source uses the MySQL database but your testing service uses the embedded HSQL database.
  • The integrating testing does not need the Spring MVC beans

Using the test profile for the RootConfigurationTest helps you filter the right Spring beans for the integration testing. And the unit test should use the profile test as the default.

One Comment

Leave a Reply

Your email address will not be published. Required fields are marked *