1

I am writing a controller test for a spring boot application. To use the spring application context I am using SpringRunner class. The problem is the main application class has a property source defined to a specific file path.

When I am running the test I am getting a FileNotFound exception from the hardcoded file. I want my test to be independent of this property source.

I cannot add the 'ignoreResourceNotFound' option for property source in the main application.

Below is the main application class with property source defined.

@SpringBootApplication
@PropertySource("file:/opt/system/conf/smto/management.properties")
@EnableConfigurationProperties
public class ManagementApp {

    public static void main(String[] args) {
        SpringApplication.run(ManagementApp.class, args);
    }

}

I am also adding my test class below

@RunWith(SpringRunner.class)
@TestPropertySource(locations = {"classpath:application.properties","classpath:management.properties"})
@DirtiesContext
@EmbeddedKafka(topics = {"management-dev"},partitions = 1,
        controlledShutdown = false,brokerProperties = {"listeners=PLAINTEXT://localhost:9092", "port=9092"})
@AutoConfigureMockMvc
@WebMvcTest(Controller.class)
public class ControllerTest {
}
Bhupad
  • 11
  • 1
  • Hi & welcome! [This](https://stackoverflow.com/q/12691812/592355) is not really "duplicate", but the [accepted answer](https://stackoverflow.com/a/14167357/592355) is also a solution to your problem. (You'd "decorate" your Tests like `@ActiveProfiles("override")`.) – xerx593 May 16 '21 at 08:41
  • Hi & Thanks @xerx593! I tried with the `@ActiveProfiles("override")` but the primary configuration class is still looking for the same file. The changes I made are, moved the test class to the older package (so main app can be found), added `@ActiveProfile("override)` on the test class, and created override.properties. same error – Bhupad May 16 '21 at 12:42

1 Answers1

0

I have found a workaround to create the spring context in this scenario. I have changed my testing class package and because of it, the spring-boot test cannot find the primary configuration class. And then provided all the required packages to create the application context.

Reference for this solution found from spring docs here.

Spring Boot’s @*Test annotations will search for your primary configuration automatically whenever you don’t explicitly define one.

The search algorithm works up from the package that contains the test until it finds a @SpringBootApplication or @SpringBootConfiguration annotated class. As long as you’ve structured your code in a sensible way your main configuration is usually found.

Bhupad
  • 11
  • 1