Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Spring's ResourceLoader in tests

I'm @Autowireing 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:

  • During tests, the @Autowired resourceLoader is an instanceof org.springframework.context.support.GenericApplicationContext
  • During regular execution, resourceLoader is an instance of org.springframework.web.context.support.XmlWebApplicationContext
like image 796
jlb Avatar asked Dec 20 '22 21:12

jlb


1 Answers

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.

like image 190
Arend v. Reinersdorff Avatar answered Jan 04 '23 23:01

Arend v. Reinersdorff