Our Article Library

  1. Growth Analytics
  2. Predictive Analytics is dead
  3. Deep Learning
  4. AI for Business Growth
  5. Healthcare Analytics
  6. Massively Scalable Applications       Slideshare       HTML
  7. Predictive Analytics
  8. Data Analytics

Part 5: Spring - jUnit Annotations

This tutorial is part 5 of 5-part tutorial on JEE annotations. We recommend that you read Prerequisite section first, review the abstract and Example Application to understand the context. You can also jump to other parts by clicking on the links below.

Spring jUnit Annotations - Contents:

AnnotationPackage Detail/Import statement
@RunWithimport org.junit.runner.RunWith;
@ContextConfigurationimport org.springframework.test.context.ContextConfiguration;
@Testimport org.junit.Test;
@DirtiesContextimport org.springframework.test.annotation.DirtiesContext;
@Timedimport org.springframework.test.annotation.Timed;

We are now ready to test our Spring based application using jUnit and Spring Unit testing framework. The following jUnit and Spring annotations will be used to accomplish this.


When a class is annotated with @RunWith or extends a class annotated with @RunWith, JUnit will invoke the class it references to run the tests in that class instead of the runner built into JUnit. Let us configure jUnit to use Spring jUnit Class runner.
public class CompanyServiceTest {


Set the spring ApplicationContext for your test classes using @ContextConfiguration annotation.
public class CompanyServiceTest {
@ContextConfiguration provides support for inheriting resource locations or configuration classes declared by superclasses by default.


Annotate all your jUnit unit tests with @Test. Also note that we can wire other spring beans in our jUnit test classes using @Autowired annotation.
  private CompanyService companyService;

  public void testFindByName() {
    Company company = companyService.findByName("techferry");
    if (company != null) {
      assertEquals("prospect", company.getStatus().getName());


Annotate @DirtiesContext to indicate that it dirties the ApplicationContext. This will trigger context reloading before execution of next test.


Indicates that the annotated test method must finish execution in a specified time period (in milliseconds). If the text execution time exceeds the specified time period, the test fails.


  1. Annotations for Unit Testing Spring applications: http://static.springsource.org/spring/docs/current/spring-framework-reference/html/testing.html#integration-testing-annotations