Spring Testing - Spring JUnit 4 Rules

[Updated: Aug 21, 2017, Created: Jul 25, 2017]

Spring 4.12 introduced two JUnit rules: SpringClassRule and SpringMethodRule.

Instead of using @RunWith(SpringRunner.class), we can use these two rules to achieve the same result.

As JUnit framework allows only one Runner in a test class, Spring JUnit rules provide the flexibility to run tests in Spring context environment without using @RunWith(SpringRunner.class), which allows us to use other JUnit runners like Parameterized in the same test class.


Creating a simple Spring application

public class ShoppingCart {
  private List<String> orders = new ArrayList<>();

  public void addItem(String name, int qty) {
      orders.add(String.format("order. Item:%s qty%s", name, qty));

  public String checkout() {
      String msg = placeOrders();
      return msg;

  public String placeOrders() {
      return orders.size() + " orders placed";
public class AppConfig {

Writing JUnit test

@ContextConfiguration(classes = AppConfig.class)
public class ShoppingCartTest {

  public static final SpringClassRule SPRING_CLASS_RULE= new SpringClassRule();

  public final SpringMethodRule springMethodRule = new SpringMethodRule();

  private ShoppingCart shoppingCart;

  public void testCheckout() {
      shoppingCart.addItem("Item1", 3);
      shoppingCart.addItem("item2", 5);
      String result = shoppingCart.checkout();
      System.out.printf("Shopping cart checkout response: %s%n", result);
      Assert.assertEquals("2 orders placed", result);
mvn -q test


D:\example-projects\spring-core-testing\spring-junit-rules>mvn -q test

Running com.logicbig.example.ShoppingCartTest
Shopping cart checkout response: 2 orders placed
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.367 sec

Results :

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0


As seen in the above example, SpringMethodRule should always be annotated with @Rule and SpringClassRule should always be annotated with @ClassRule. That's because SpringMethodRule supports instance level features, whereas, SpringClassRule supports class level features.

Example Project

Dependencies and Technologies Used :

  • spring-context 4.3.9.RELEASE: Spring Context.
  • spring-test 4.3.9.RELEASE: Spring TestContext Framework.
  • junit 4.12: JUnit is a unit testing framework for Java, created by Erich Gamma and Kent Beck.
  • JDK 1.8
  • Maven 3.3.9

Spring Junit Rules Example Select All Download
  • spring-junit-rules
    • src
      • main
        • java
          • com
            • logicbig
              • example
      • test
        • java
          • com
            • logicbig
              • example

See Also