开发者

Changing resource files dynamically for testing

I have a program that relies on an XML file to retrieve data from. When testing, I would like it to use a different XML file.

I would like to do this using Cl开发者_StackOverflowassLoader, where the code may be similar to something along the lines of this:

ClassLoader loader = Thread.currentThread().getContextClassLoader();

Using loader, I would load the testing XML resource file. So all operations using the default XML file would instead be using the testing XML file.

How would I go about doing this?


You have different options for this, you can create different jar-files e.g. testing.jar and production.jar and put the corresponding file into these files. Get an InputStream with

InputStream is = loader.getResourceAsStream(resourceName);

Or you create a helper class, which is searching a File first, then trying to get the InputStream from the ClassLoader. If the file (with the right path) is available in your development environment you get the testing XML, in production environment the file should not be available so you get the production XML from the resource bundle (jar).

If you are using Maven, you have different resources (src/main/resources and src/test/resources) available.


If your XML is used to popolate some configuration object and the purpose of your tests are to test the application with a different configuration - I recommend changing the approach: You would be better off mocking the configuration object and using the mock in the tests.

I believe that if you use MockIt, you will not even need to change your application to make it possible.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜