views:

41

answers:

2

Hello everyone!

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 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?

+3  A: 

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.

Jon Skeet
Hmmmmm.... might need to do some re-factoring to make this work... Although it does seem to be a better solution than mixing configuration and logic like I am currently...
KLee1
+1  A: 

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.

pcjuzer