I have a simple unit test, and I'd like for the unit tests to load up a test property file that I've placed in src/test/resources/test.properties
instead of the property file in src/main/resources/application.properties
.
My test class is set up as follows:
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
@TestPropertySource(locations = "classpath:src/test/resources/properties-test.yml")
public class SecurityConfigurationTest {
@MockBean
KafkaConfiguration kafkaConfiguration;
@MockBean
KafkaMonitor kafkaMonitor;
@MockBean
BuildProperties buildProperties;
@Autowired
MockMvc mockMvc;
@Test
public void unauthorizedUser_shouldNotAccessHomePage() throws Exception{
mockMvc
.perform(get("/"))
.andExpect(status().isUnauthorized());
}
}
My project file structure is as shown below:
But I am getting the following error, suggesting I'm not specifying this property file correctly:
Caused by: java.io.FileNotFoundException: class path resource [src/test/resources/test.properties] cannot be opened because it does not exist
How do can I manage to get the test.properties
file to be used instead of the application.properties
file for my unit tests?
CodePudding user response:
In pom.xml add a profiles tag which specifies which properties file should the program choose when it runs.
<profiles>
<profile>
<id>test</id>
<properties>
<activatedProperties>test</activatedProperties>
</properties>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
</profiles>
Note: name of your properties file must be application-test.properties.
This will make your test properties active but to access it you need to configure your test resource folder and let the intellij know 'use this when running.
In Intellij, you can change your resource folder with which you run your project, so you need to....
- Select test resource folder.
- Right click on it. In the opened menu, select Modify Run Configuration and create a new configuration.
This means a new Run Configuration is created for running test resource folder.
- Run the configuration.
CodePudding user response:
Maven by default will package all files in the src/test/resources/
folder to the classpath. So to refer it by the classpath , it should be :
@TestPropertySource(locations = "classpath:properties-test.yml")
Alternatively, if you want to refer it by the system file path , you can change it to :
@TestPropertySource(locations = "file:src/test/resources/properties-test.yml")
Under the cover , its uses ResourceLoader
to load the file. See this for more details.