Best Practice Changing Spring Implementation Object in JUnit Test

java, junit, spring

Solution

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"})

Problem

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: - split the context (defaultContext, emContext) and override context file by test context file (emContext in test resources) - use factory and choose testEntityManager (in production code) - 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.

Original source