aspose file tools*
The moose likes Spring and the fly likes How do I get an ApplicationContext reference in a JUnit test? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Frameworks » Spring
Bookmark "How do I get an ApplicationContext reference in a JUnit test?" Watch "How do I get an ApplicationContext reference in a JUnit test?" New topic
Author

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

Dave Alvarado
Ranch Hand

Joined: Jul 02, 2008
Posts: 436
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).
Bill Gorder
Bartender

Joined: Mar 07, 2010
Posts: 1649
    
    7

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.



[How To Ask Questions][Read before you PM me]
Dave Alvarado
Ranch Hand

Joined: Jul 02, 2008
Posts: 436
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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: How do I get an ApplicationContext reference in a JUnit test?