I have been encountering an issue where AnsibleConfig.java, located in the commons module, is not being properly initialized or accessed during tests in the main module of your Spring Boot application. Despite configuring @SpringBootTest with @ActiveProfiles(“test”), and ensuring application-commons.properties is correctly placed in src/test/resources of the commons module, AnsibleConfig.java remains null during test execution. The main module runs the Spring Boot application with its @SpringBootApplication class and public static void main method, while other modules like commons provide configurations. Despite these configurations, AnsibleConfig.java fails to initialize properly in tests and its probably user error.
I’m needing to access the AnsibleConfig.java from the mainapp module.
When I try to run the tests, the compiler says Ansibleconfig is null. If someone can point me to the right direction I would appreciate it.
Here is the layout of my project:
project:
commons:
src/main/app/config:
* AppConfig.java (annotated with @Configuration)
src/main/app/other:
* AnsibleExecutor.java
src/main/resources:
* application-commons.properties
* application-commons-test.properties
mainapp:
/src/main/app:
* main.java ( has @SpringbootApplication)
* EvenLoader.java
/src/main/resources:
* application-main.properties
* application-main-test.properties
/src/test/app:
* mytests.java
//AnsibleConfig.java
@Configuration
@ConfigurationProperties(prefix = "common.ansible")
@PropertySource("classpath:application-commons.properties")
@Primary
@Getter
public class AnsibleConfig {
@Value("${inventory-file-path}")
private Path inventoryFilePath;
@Value("${playbooks-folder-path}")
private Path playbooksFolderPath;
@Value("${identity-file-path}")
private Path identityFilePath;
}
//properties-common-test.properties
[email protected]@/resources/ansible/inventories}
[email protected]@/resources/ansible/playbooks}
[email protected]@/resources/ansible/.auth/ansible_id_rsa}
\MyTests.java
@SpringbootTest
@ActiveProfiles("test")
class MyTests {
@Test
void there() {
Map<String, Host> hosts = EventLoader.getHosts();
Assertions.assertTrue(hosts.size() >= 1);
Assertions.assertTrue(hosts.containsKey("nwrd"));
}
}
\EventLoader.java <- mainapp
@Slf4j
@Component
public class EventLoader {
public static Map<String, Event> load() {
File playbooks =
AnsibleExecutor.getPlaybooksPath().resolve("events").toFile();
}
}
\AnsibleExecutor.java <- from commons ( added commons as dependency)
@Slf4j
@Service
@EnableConfigurationProperties(AnsibleConfig.class)
public class AnsibleExecutor {
private static AnsibleConfig appConfig;
private static final ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
private static final CommandExecutor commandExecutor = new CommandExecutor();
@Autowired
AnsibleExecutor(AnsibleConfig config){
appConfig = config;
}
public static Path getPlaybooksPath() {
return appConfig.getPlaybooksFolderPath();
}
}