Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

spring java configuration unit test

Tags:

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); 
like image 637
user373201 Avatar asked Dec 27 '11 03:12

user373201


People also ask

How do you write a Unit Test for spring boot?

The @Profile(“test”) annotation is used to configure the class when the Test cases are running. Now, you can write a Unit Test case for Order Service under the src/test/resources package. The complete code for build configuration file is given below.

What is @configuration spring boot?

Spring @Configuration annotation is part of the spring core framework. Spring Configuration annotation indicates that the class has @Bean definition methods. So Spring container can process the class and generate Spring Beans to be used in the application.

How do you use ConfigurationProperties in a test?

Basically, you: use a specific configuration to @EnableConfigurationProperties and @EnableAutoConfiguration , listing all the @ConfigurationProperties files you want to load. in the test class, you load this configuration file of tests, with an initializer class defined by Spring to load application. yml file.


1 Answers

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)

like image 131
Chris Beams Avatar answered Nov 09 '22 20:11

Chris Beams