Categorize tests to reduce build time

Before we progress with the main content of the article, let’s get a few definitions out of the way.

Unit tests

Unit tests are tests that are small (tests one use case or unit), run in memory (do not interact with database, message queues etc.), repeatable and fast. For our conversation let us restrict these to JUnit based test cases that developers write to check their individual piece of code.

Integration tests

Integration tests are larger (tests one flow or integration of components), do not necessarily run in memory only (interact with database, file systems, message queues etc.), definitely slower, and not necessarily repeatable (as in the result might be change in case some change was done in data base for example).

Why is this differentiation important?

In Agile programming, on of he basic concepts is to run unit tests every once in a while (multiple times in a day on developer boxes) and enforce the integration tests to run once a day (on continuous integration server rather than on developer boxes). Please note that the developer should be able to run integration tests whenever he wants it, it is just that it is separate from the unit tests so the developer now have a choice to not run integration tests every time he wants to run tests.

How exactly does that flexibility help?

  1. Developers build more frequently. That – in Agile world means – developers run unit tests more frequently (often a few times per day).
  2. Developers get to know of a bug sooner and waste less time coding to a broken codebase. That means saving time and money.
  3. Fixing bugs is easier and faster. Given the frequency of builds, less amount of “offending code” could have been committed and hence it is easier to zero down on the bug and fix it.
  4. Last but not the least, anyone who has done any professional coding will testify that while it helps to be able take a 10 minute break once in a while, nothing kills the creativity of a coder more efficiently than having to wait for a 1 hour build. The impact to morale is intangible, but immense.

How exactly do I bring down the build time?

There is no one size fits all (there never is). The exact executable steps to bring down build and release time will be a factor of many variables including the technology stack of the product (Java, DotNet, php), the build and release technologies (Batch files, Ant, Maven) and many other.

For Java, Maven, and JUnit combination …

Let us start by using Maven to create a simple java application to demonstrate the case.

\MavenCommands.bat

ECHO OFF 

REM =============================
REM Set the env. variables. 
REM =============================
SET PATH=%PATH%;C:\ProgramFiles\apache-maven-3.0.3\bin;
SET JAVA_HOME=C:\ProgramFiles\Java\jdk1.7.0

REM =============================
REM Create a simple java application. 
REM =============================
call mvn archetype:create ^
  -DarchetypeGroupId=org.apache.maven.archetypes ^
  -DgroupId=org.academy ^
  -DartifactId=app001
pause

If you run this batch file you will start with a standard java application readymade for you.

The default java application does not come with the latest JUnit. You might want to change Maven configuration to add latest JUnit.

\pom.xml

[...]

                    
                     4.10
                    
[...]
                    

                                               

                     
                      junit
                                

                     
                      junit
                          

                     
                      ${junit.version}
                     

                     
                      test
                                     

                    

Now, go ahead and add a JUnit test class.

/app001/src/test/java/org/academy/AppTest.java

public class AppTest {

private final static Logger logger = LoggerFactory.getLogger(AppTest.class);

@Test
public void smallAndFastUnitTest() {
 logger.debug("Quick unit test. It is not expected to interact with DB etc.");
 assertTrue(true);
}

@Test
@Category(IntegrationTest.class)
public void longAndSlowIntegrationTest() {
 logger.debug("Time consuming integration test. It is expected to interact with DB etc.");
 assertTrue(true);
}
}

As you might notice there is a IntegrationTest.class marker. You will have to create this class as well.

/app001/src/test/java/org/academy/annotation/type/IntegrationTest.java

public interface IntegrationTest {
  // Just a marker interface. 
}

Creating the marker interface and annotating your test methods (or classes if you choose to) is all that you have to do in your code.

Now, all that remains to be done is to tell maven to run “integration tests” only at integration test phase. That means a developer could choose to run only the unit tests (the fast ones that are insulated from databases, queues etc) for most of the time. The Continuous Integration server i.e. Hudson (or the likes) will run the unit tests and the integration tests (which will be slower since they are expected to interact with databases etc.) and that can happen overnight.

So, here is how you do it.

/pom.xml

                                                        

                                                                                                
 
                     
                      org.apache.maven.plugins
                                                          
 
                     
                      maven-surefire-plugin
                                                       
 
                     
                      2.12
                                                                              

                                                                                       
 
                                                                                      
  
                       
                        org.apache.maven.surefire
                                                   
  
                       
                        surefire-junit47
                                                      
  
                       
                        2.12
                                                                        
 
                                                                                     

                                                                                      

                                                                                      
 
                      
                       -XX:-UseSplitVerifier
                                                      
 
                      
                       org.academy.annotation.type.IntegrationTest
                      

                                                                                     

                            

This will mean that a developer can run all the unit tests just by using one liner.

mvn clean test

This will not run any test that is annotated as integration test.

For integration test add the following.

/pom.xml

                                 

                                                                                
 
                     
                      maven-failsafe-plugin
                                       
 
                     
                      2.12
                                                              
 
                                                                       
  
                                                                      
   
                       
                        org.apache.maven.surefire
                                   
   
                       
                        surefire-junit47
                                      
   
                       
                        2.12
                                                        
  
                                                                     
 
                                                                      
 
                                                                      
  
                      
                       org.academy.annotation.type.IntegrationTest
                      
 
                                                                     
 
                                                                         
  
                                                                       
   
                                                                        
    
                        
                         integration-test
                                               
   
                                                                       
   
                                                                
    
                                                                  
     
                         
                          **/*.class
                                            
    
                                                                 
   
                                                               
  
                                                                      
 
                                                                        

                    

This means the Hudson or the developer (if he chooses to) can run all the tests, unit and integration by a single command.

mvn clean verify    

Of course if you choose to go all the way i.e. compile, run unit tests, package, run integration tests and deploy, you could do that with a single line of command as well.

mvn clean deploy

That’s it. You have taken one step towards faster builds and more agile way of working. Happy coding.

Further reading

  • A version of this article – slightly edited, is also available at this link at Javalobby.
  • Here is another article which covers a similar topic using same technique.

Reference: Categorize tests to reduce build time. from our JCG partner Partho at the Tech for Enterprise blog.

Related Whitepaper:

Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expressions

Get ready to program in a whole new way!

Functional Programming in Java will help you quickly get on top of the new, essential Java 8 language features and the functional style that will change and improve your code. This short, targeted book will help you make the paradigm shift from the old imperative way to a less error-prone, more elegant, and concise coding style that’s also a breeze to parallelize. You’ll explore the syntax and semantics of lambda expressions, method and constructor references, and functional interfaces. You’ll design and write applications better using the new standards in Java 8 and the JDK.

Get it Now!  

One Response to "Categorize tests to reduce build time"

  1. Peter Dodok says:

    you poms file are corupted

Leave a Reply


3 − two =



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books