I have JUnit tests that need to run in various different staging environments. Each of the environments have different login credentials or other aspects that are specific to that environment. My plan is to pass an environment variable into the VM to indicate which environment to use. Then use that var to read from a properties file.
Does JUnit have any build in capabilities to read a .properties file?
You can use @TestPropertySource annotation in your test class. Just annotate @TestPropertySource("classpath:config/mailing. properties") on your test class. You should be able to read out the property for example with the @Value annotation.
properties file in the classpath (src/main/resources/application. properties).
JUnit provides static methods to test for certain conditions via the Assert class. These assert statements typically start with assert. They allow you to specify the error message, the expected and the actual result. An assertion method compares the actual value returned by a test to the expected value.
Basically, you: use a specific configuration to @EnableConfigurationProperties and @EnableAutoConfiguration , listing all the @ConfigurationProperties files you want to load. in the test class, you load this configuration file of tests, with an initializer class defined by Spring to load application. yml file.
It is usually preferred to use class path relative files for unit test properties, so they can run without worrying about file paths. The path may be different on your dev box, or the build server, or where ever. This will also work from ant, maven, eclipse without changes.
private Properties props = new Properties(); InputStream is = ClassLoader.getSystemResourceAsStream("unittest.properties"); try { props.load(is); } catch (IOException e) { // Handle exception here }
putting the "unittest.properties" file at the root of the classpath.
java has built in capabilities to read a .properties file and JUnit has built in capabilities to run setup code before executing a test suite.
java reading properties:
Properties p = new Properties(); p.load(new FileReader(new File("config.properties")));
junit startup documentation
put those 2 together and you should have what you need.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With