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.

@RunWith

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.
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"/spring-servlet-test.xml"})
public class CompanyServiceTest {
...
}

@ContextConfiguration

Set the spring ApplicationContext for your test classes using @ContextConfiguration annotation.
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"/spring-servlet-test.xml"})
public class CompanyServiceTest {
...
}
@ContextConfiguration provides support for inheriting resource locations or configuration classes declared by superclasses by default.

@Test

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.
  @Autowired
  private CompanyService companyService;

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

@DirtiesContext

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

@Timed

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.
@Timed(millis=1000)

References

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