Java Learing
Java Learing

Reputation: 271

How to configure SpringConfig.java file for JUnit testing

I am using SpringConfig.java instead of SpringConfig.xml. In this class I return:

 @Bean(name = "restTemplate")
        public RestTemplate restTemplate() {
            return new RestTemplate();
        }

instead of writing

And I am using @Autowired and I am using SpringJunit4Classrunner. How can I configure SpringConfig.java and my JUnit test file to do proper dependency injection.

Upvotes: 0

Views: 1530

Answers (2)

mps98
mps98

Reputation: 93

If you want to use only annotations, you don't have to use @Autowired in other classes, all configurations have to be in SprinConfig.java. have a look in
SpringConfig Annotations

For Junit Configuration, you have to configure dependencies in pom.xml like this:

<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.12</version>
  <scope>test</scope>
</dependency>

and your test class will be like this:

import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import package.SpringConfig;

public class SimpleTests {

@Test
public void Test() {

    AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(
            SpringConfig.class);
//...
}

Upvotes: 1

Fritz Duchardt
Fritz Duchardt

Reputation: 11860

Place the following annotations above your class delcaration in your unit test:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class),

Upvotes: 0

Related Questions