0

I want to initialize Spring once and only once in my application/running code (and I do that in the main(String[] args method).

Now I am writing tests, I also want to init only once in my unit test code (but it should already be init'd for my application to run. How do I structure my code/classs so that I would not have to cut-copy-paste code from my app code into my test code and reuse the same Spring context that is init'd in main()?

In other words, I would have to be init'd in the application code and then somehow passed to my unit or system test code so that it has the same instance of 'context' throughout.


I am initializing the Spring context in a

public static void main(String[] args) {
   ...
   ApplicationContext context =
      new AnnotationConfigApplicationContext(SpringConfig.class);
   ...
}

Thanks

J.V.

Matthew Farwell
  • 60,889
  • 18
  • 128
  • 171
Jay Vee
  • 569
  • 1
  • 4
  • 6
  • Unit tests are not running in the same JVM as your application. They can't share the same context. Just create a new context in your tests, the same way as you're doing in your main. – JB Nizet Aug 13 '14 at 22:02
  • @JBNizet They the context will be "inited" multiple times which is what the OP is attempting to avoid. – John B Aug 14 '14 at 11:31

1 Answers1

1

You could set up a @Rule. Use a singleton instance across all your tests. Have the rule maintain state and on first invocation set up the Spring context. All other tests would just use the existing context. Expose the context via a getter so that tests can use the context to retrieve beans.

In response to your comment... First here is a link to check out: Rules Wiki - Custom Rules

  • Normally when you use a Rule you create the Rule instance for each class. In this case you would want to use a singleton so implement your Rule as a singleton class with a static getInstance method that the tests would use to share the single instance.
  • If you use the same instance (singleton) for all the tests and have it hole as a field the Spring context, you have state.
  • Have the Rule create and start the Spring context and have a getter that returns the context so that your tests can have access to the context.
  • The getter goes in the Rule.
John B
  • 32,493
  • 6
  • 77
  • 98
  • I almost understand what you are saying; I will work on some code but if you have code examples that would be great. I have never used @Rule, by default everything is a singleton so not sure what I would have to do there. How do I make the Rule maintain state (what needs to be done) and how is the rule first invoked? How do the tests use the existing context (how does the test get access to the existing context) Where does the getter go (example class). – Jay Vee Aug 14 '14 at 20:26