Junit with Spring

Key Points

  • If test case class “extends TestCase”, it’s a JUnit 3.x test class. JUnit 4.x classes don’t need to inherit from anything, they use @Test annotations.
  • Ways to a make a test class Spring4 test:
    Option 1
    Extend AbstractTransactionalJUnit4SpringContextTests – Abstract base test class which integrates the Spring TestContext Framework with explicit ApplicationContext testing support in a JUnit environment.

    Option 2
    Add these annotations to your test class:

    @TestExecutionListeners( { DependencyInjectionTestExecutionListener.class,
    DirtiesContextTestExecutionListener.class })

TestExecutionListeners are a way to externalize reusable code that instruments your tests.

As such, if you implement a TestExecutionListener you can reuse it across test class hierarchies and potentially across projects, depending on your needs.

On the flip side, a @BeforeClass method can naturally only be used within a single test class hierarchy.

Note, however, that JUnit also supports Rules: if you implement org.junit.rules.TestRule you can declare it as a @ClassRule to achieve the same thing… with the added benefit that a JUnit Rule can be reused just like a Spring TestExecutionListener.

So it really depends on your use case. If you only need to use the “before class” functionality in a single test class or a single test class hierarchy, then you’d be better off going the simple route of just implementing a @BeforeClass method. However, if you foresee that you will need the “before class” functionality in different test class hierarchies or across projects, you should consider implementing a custom TestExecutionListener or JUnit Rule.

The benefit of a Spring TestExecutionListener over a JUnit Rule is that a TestExecutionListener has access to the TestContext and therefore access to the Spring ApplicationContext which a JUnit Rule would not have access to. Furthermore, a TestExecutionListener can be automatically discovered and ordered.

  • Spring automatically wraps test methods in rollback-only transactions when test-case class is annotated with @Transactional. This has certain benefits: you won’t corrupt your database during the test and each test works on the same data, so you are not introducing inter-test dependencies.


Spring provides SpringJUnit4ClassRunner that implements the functionality of JUnit4ClassRunner. JUnit4ClassRunner is provided by JUnit. It implicitly provides access to ApplicationContext, just add in test class:
private ApplicationContext applicationContext;
Also with this test class doesn’t have to extend JUnit class such as AbstractJUnit4SpringContextTests.

@ContextConfiguration(classes = AppConfig.class)
@ContextConfiguration annotation uses the application context being used in the application. By default, ApplicationContext for a test class will be loaded from “classpath:/path/to/class/<TestClassName>-context.xml”

@Transactional annotation tells the test case that if transaction does not complete then revert other transactions.

@TransactionConfiguration(defaultRollback = true)
Suppose if transaction is completed successfully, and test case has finished the data testing and then if we want to remove it from database, then TransactionConfiguration annotation works. To achieve it defaultRollback must be true.

Annotation Use Description
@AfterTransaction Method Used to identify a method to be invoked after a transaction has completed.
@BeforeTransaction Method Used to identify a method to be invoked before a transaction starts.
@ContextConfiguration Type Configures a Spring application context for a test.
@DirtiesContext Method Indicates that a method dirties the Spring container and thus it must be rebuilt after the test completes.
@ExpectedException Method Indicates that the test method is expected to throw a specific exception. The test will fail if the exception is not thrown.
@IfProfileValue Type, Method Indicates that the test class or method is enabled for a specific profile configuration.
@NotTransactional Method Indicates that a test method must not execute in a transactional context.
@ProfileValueSourceConfiguration Type Identifies an implementation of a profile value source. The absence of this annotation will cause profile values to be loaded from system properties.
@Repeat Method Indicates that the test method must be repeated a specific number of times.
@Rollback Method Specifies whether or not the transaction for the annotated method should be rolled back or not.
@TestExecutionListeners Type Identifies zero or more test execution listeners for a test class.
@Timed Method Specifies a time limit for the test method. If the test does not complete before the time has expired, the test will fail.
@TransactionConfiguration Type Configures test classes for transactions, specifying the transaction manager and/or the default rollback rule for all test methods in a test class.

Testing Spring MVC

Access Spring application context in JUnit 4 tests

Access Spring application context in JUnit 4 tests


One comment

  1. I’m now not sure where you’re getting your info, but great topic. I needs to spend a while learning much more or understanding more. Thanks for wonderful info I used to be in search of this info for my mission.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s