Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does JUnit support properties files for tests?

Tags:

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?

like image 323
Dave Jensen Avatar asked Oct 12 '09 23:10

Dave Jensen


People also ask

How does Spring Boot read properties file in test class?

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.

Where does spring boot look for property file in test?

properties file in the classpath (src/main/resources/application. properties).

What can be tested using JUnit?

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.

How do you use ConfigurationProperties in a test?

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.


2 Answers

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.

like image 179
scott m gardner Avatar answered Jan 22 '23 05:01

scott m gardner


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.

like image 31
pstanton Avatar answered Jan 22 '23 05:01

pstanton