Thursday, December 29, 2011

Unit Test on Spring via Maven - configuration tips



 This post is for newbies who set their project to run Spring powered Unit Tests via Maven.

There are many blogs who mention how to do it.
I would recommend to install STS IDE and create new Spring Template project.
It usually comes with built in Test package. The test package can be executed via JUnit.

The tricky part comes when you want to run the tests via Maven and set the Spring configuration xml file in your custom folder.

Using default setting, Maven might raise an exception complaining the Spring xml configuration file could not be found or Tests could not be found.

So, my two cents are:
cent 1: Make sure your test classes ends with Test (and not ending with Tests, for example, as it comes with the Spring default project)
cent 2: configuration can be resolved while defining the spring configuration path.
 The trick is to use the relative location as it is in the source folder, and not in the target compilation folder. Also note to use backslash as folder separation and not dots.

Configuration using classpath relative path:

@ContextConfiguration (value = "classpath:/com/company/app/OrderPersistenceTests-context.xml")

 @RunWith(SpringJUnit4ClassRunner.class)

public class OrderPersistenceTest {

...

}

or

Configuration using project relative path:

@ContextConfiguration (value = "file:src/test/resources/com/company/app/OrderPersistenceTests-context.xml ") 
@RunWith(SpringJUnit4ClassRunner.class)
public class OrderPersistenceTest {



...

} 


Run tests using maven:
If pom.xml has the skipTest tag with true as value, e.g.:

       

            

                org.apache.maven.plugins

                maven-surefire-plugin

                2.6

                 

                1.5

                1.7

               true

            

            

...


...

Then no test will be executed, even when explicitly executing maven with test goal


Good luck !

No comments :

Post a Comment