Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best Practice Changing Spring Implementation Object in JUnit Test

Tags:

java

junit

spring

I have a Spring-enabled JUnit Test. It loads my default applicationContext. Now I want to replace a single bean for my test, i.e. entityManager with testEntityManager.

I can imagine three possible ways, which don't seem very elegant:

  1. split the context (defaultContext, emContext) and override context file by test context file (emContext in test resources)
  2. use factory and choose testEntityManager (in production code)
  3. not to use Spring, but build the object hierarchy myself (least feasible solution)

Is there a best practice how to do it right?

Background to this question is: I really only want to replace the objects close at the boundary (DB, Webservices, etc)

Yours Sincerely

EDIT: I have solved it this way now: I added a properties file to my classpath and test classpath and used a Spring alias in conjunction with a property placeholder. This way I was able to wire my beans to a different implementation in the tests.

like image 350
lastcosmonaut Avatar asked Aug 21 '12 11:08

lastcosmonaut


People also ask

Which of the following is advisable to use after every test or object identified with the @after JUnit annotation?

@Before – Run before @Test, public void. @After – Run after @Test, public void.

Which of the following is correct about test suite in JUnit?

Which of the following is correct about Test Suite in JUnit? Explanation: Test suite allows us to aggregate a few unit test cases from multiple classes in one place and run them together. @RunWith and @Suite annotation are used to run the suite test.


1 Answers

Spring allows you to override bean definitions, when you are loading contexts from multiple locations.

So you don't necessarily need to to split the context "/applicationContext.xml". Instead have an additional application context for test "/applicationContext-test.xml", where you override the bean you need. Then pull in both configurations and have the bean in the test configuration override the bean in the production configuration.

@ContextConfiguration({"/applicationContext.xml", "/applicationContext-test.xml"})
like image 125
Dan Avatar answered Nov 10 '22 11:11

Dan