Setting Environment Variables for All JUnit Tests in Eclipse
I am trying to set up some unit tests, which use the database. I would like to use a test database on the developer's computer instead of on the production database. The method I have in place now is to check an environment variable开发者_JAVA技巧 when connecting to the database, and if that variable exists to connect to the local one instead of the production one.
I can set environment variables in Eclipse through the Run Configurations, but I want this to happen whenever a JUnit test is run (just in case).
Is this possible in Eclipse?
Why don't you inject the database connection into the logic which needs testing, and only deal with environment variables in your startup code (which generally doesn't need unit testing)?
Using environment variables in tests is generally a sign that configuration is happening too deeply inside your code, IME. Where possible, I find it much better to construct objects with everything they need via dependency injection, keeping that code separate from the configuration code which works out what to inject.
I think hard-coding connection info or test/production switch is not the best idea.
Basically, we have DB connection information in property file. At unit testing, we use another property file which contains connection info for test database. (A lightweight in-memory DB may be optimal for unit testing.)
Unit tests usually have their own setup fixtures which composes a basic environment for each test cases, so it shouldn't be a problem to use a dedicated property file.
精彩评论