user373201
user373201

Reputation: 11435

spring java configuration unit test

I am trying out spring's java configuration. While using xml config files my unit tests use to have the following

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(....)

If I am using java configuration, How do i do it. or should I just use

ApplicationContext appConfig = new  AnnotationConfigApplicationContext(SimpleConfiguration.class);

Upvotes: 24

Views: 28545

Answers (2)

Chris Beams
Chris Beams

Reputation: 1483

As of Spring 3.1, @ContextConfiguration now has full support for @Configuration classes; no XML required.

See http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/htmlsingle/spring-framework-reference.html#d0e1392

Or more specifically, http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/htmlsingle/spring-framework-reference.html#testcontext-ctx-management-javaconfig, which shows the following code snippet:

@RunWith(SpringJUnit4ClassRunner.class)
// ApplicationContext will be loaded from AppConfig and TestConfig
@ContextConfiguration(classes={AppConfig.class, TestConfig.class})
public class MyTest {
    // class body...
}

AppConfig and TestConfig are @Configuration classes (aka "Java config" classes in @user373201's comments)

Upvotes: 31

Aravind A
Aravind A

Reputation: 9697

@ContextConfiguration is used to load the Spring configurations while you are working with test cases . If you don't need it , you could use ClassPathXmlApplicationContext to load the Spring configuration .

Use the constructor which takes in configuration locations as String array .

AnnotationConfigApplicationContext is used to auto detect the annotated classes . I don't think it can be used to load configuration files . It is similar to context:component-scan

SpringJUnit4ClassRunner provides Spring Test support for Junit via annotations like @Test.

Upvotes: 3

Related Questions