I'm @Autowire
ing a org.springframework.core.io.ResourceLoader
into one of my @Service
classes.
During the tests, I'd like to get access to an instance of a ResourceLoader
, so that it can be injected into the service being tested. What's the best way to get a fully functional instance of ResourceLoader
during your tests?
If that's not possible, is there an alternative to ResourceLoader
? Essentially, I need to have my service read some static files from the project.
Update:
Started using @RunWith(SpringJUnit4ClassRunner.class)
+ @ContextConfiguration
on my test; however, the ResourceLoader
that is now being injected via @Autowire
into my service behaves differently than usual (ie. when it's not in the test context). In the test, ResourceLoader#getResource
returns a Resource pointing to bad relative path, rather than the proper absolute path which appears during a regular execution.
Some more information discovered while debugging:
resourceLoader
is an instanceof org.springframework.context.support.GenericApplicationContext
resourceLoader
is an instance of org.springframework.web.context.support.XmlWebApplicationContext
You can use a DefaultResourceLoader. It handles URL and classpath resources which should be enough for simple tests.
DefaultResourceLoader doesn't need any special setup. Just create a new instance and pass it into your test.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With