• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Tim Cooke
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
  • Rob Spoor
  • Junilu Lacar
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Piet Souris
  • Carey Brown
Bartenders:

How do I get an ApplicationContext reference in a JUnit test?

 
Ranch Hand
Posts: 436
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

I'm using Spring 3.1.0.RELEASE and JUnit 4.8.1. I'm trying to debug some setup problems and so I'd like to list all the beans my application context is loading up. Within JUnit, how do I get a reference to the application context? I'm setting up my JUnit test like so …



but when I tried to list all the bean names like this



nothing was printed out (except the lines before and after the loop).
 
Bartender
Posts: 1682
7
Android Mac OS X IntelliJ IDE Spring Linux
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
OK first of all don't load the context with file rather use classpath



For the second bit I can't think of very many use cases where you would ever want to do something like this. Exactly what is it you are trying to test? You are going about this in the wrong way but you would have to provide me with a bit more context to provide more help.

As for why you are not seeing anything printed, it is because you are not loading things correctly.


Now most of the time you would not use a GenericApplicationContext you would use a ClassPathXmlApplicationContext which is much easier to set up, but for a test case you would not use either. That is the whole point of this line



That line of code initializes your context for the test case. If you really want a handle to the ApplicationContext for some reason (I would say you should not) then @Autowire in ApplicationContext.

 
Dave Alvarado
Ranch Hand
Posts: 436
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi, Thanks for your feedback. I was originally trying to figure out why certain beans weren't getting wired and so I wanted to see what was in the application context. The problem turned out to be something else -- a bean wasn't instantiated correctly because it couldn't get a JNDI reference.

I have followed your suggestion about using the "classpath:" instead of the "file:" directive in the context setup, though. - Dave
reply
    Bookmark Topic Watch Topic
  • New Topic