2

I'm doing some integration tests with JUnit. I have an xml file where I declare some template entities which I want to inject. On every test, I need a fresh application context, that is no test should depend/couple with other tests, so on setUp() I need to 're-initialize' these entities on their default starting values.

I can achieve it through reloading, but this way I can't use @Autowired annotations.

@Before
public void setUp(){        
    ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:entityTemplates-Context.xml");
    homeA = (Home)ctx.getBean("homeA");
}

Is there a way to do this and still use @Autowired for these entities?

2 Answers 2

2

Have you looked at Spring's support for integration testing?

http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/testing.html

My team use this for our integration tests where we need a Spring container. You get a fresh context per test, though this slows down the tests significantly.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I use spring-test too and after some sniffing just found '@DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD)', it does the job, it reloads the whole context, slow but only for integration tests.
0

You can also do it manually like this:

  ...
  @Autowired
  HomeA homeA;

  @Before
  public void setUp() {
    // configures this test instance as a regular spring bean
    ctx.getAutowireCapableBeanFactory().autowireBean(this);

    // here homeA is available
  }
  ...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.