Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unit testing with code that depends on environment variable

We have small set of environment variables exposed to control our application behavior. Application code is in java. (Environment variables may be evil, but the have a purpose in this special case)

What is the best way to unit test this? How can I create environment variables, set it to different values and call the tests repeatedly?

Current solution is to use env element in junit tasks . For example below

 <env key="BASE_PLUGINS_FOLDER" value="c:/temp"/>

code sets environment variable for the test. (This works only when fork mode is set to true)

This means I have to create multiple test sections in ant build file and corresponding test else where. This could become unmanageable pretty fast.

I feel there could be a better way, that is fully a junit-java code. Not sure how.

like image 526
Jayan Avatar asked Jan 29 '26 04:01

Jayan


1 Answers

You should encapsulate how you retrieve these variables. Not only will it allow you to change the way you pass them around (env variable, system properties, configuration file, etc...) but it will also more testable.

Then you can define two different implementations: one that actually reads the environment (which you use in production) and one where you can specify these values yourself in Java (which you use in your tests).

like image 193
Cedric Beust Avatar answered Feb 02 '26 12:02

Cedric Beust



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!