5

Is it possible to run test suite with loaded spring context, something like this

@RunWith(Suite.class)
@SuiteClasses({ Test1.class, Test2.class })
@ContextConfiguration(locations = { "classpath:context.xml" }) <------
public class SuiteTest {
}

The code above obviously wont work, but is there any way to accomplish such behavior?

This is currently how spring context is used in my test suite:

@BeforeClass
public static void setUp() {
    final ConfigurableApplicationContext context =
            loadContext(new String[] { "context.xml" });
    jdbcTemplate = (JdbcTemplate) context.getBean("jdbcTemplate");
    // initialization of other beans...
}
Marko Vranjkovic
  • 6,481
  • 7
  • 49
  • 68

1 Answers1

10

I have tried you code, the test suite are running with spring context loaded. Can you explain in more detail what the problem is?

here is the code:

@RunWith(Suite.class)
@SuiteClasses({ Test1.class, Test2.class })
public class SuiteTest {
}

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:context.xml" })
@Transactional
public class Test1 {}

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:context.xml" })
@Transactional
public class Test2 {}

If you want Suite class to have its own application context, try this:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:context.xml" })
@Transactional
public class SuiteTest {

    @Test public void run() {
        JUnitCore.runClasses(Test1.class, Test2.class);
    }

}
Septem
  • 3,614
  • 1
  • 20
  • 20
  • 1
    well I want Suite class to have its own application context – Marko Vranjkovic Jul 05 '13 at 08:33
  • if it's done with `JUnitCore.runClasses` then it's ordinary JUnit test not a test suite – Marko Vranjkovic Jul 05 '13 at 09:15
  • why do we need to put ContextConfiguration annotation in each test class ? – Mehdi May 14 '18 at 10:03
  • Spring intelligently caches the application context for a test suite – typically when we execute tests for a project, say through ant or maven, a suite is created encompassing all the tests in the project. https://www.javacodegeeks.com/2012/09/spring-testing-support-and-context.html – Amol Patil Jul 01 '19 at 05:22