How to mock property source in spring test?

Viewed 3344

I'm writing unit tests for my controller and faced an issue that desktop.properties file doesn't exist on my build server and shouldn't exist there.

I have this main SpringBoot class:

@Configuration
@ComponentScan(basePackages="com.xxx")
@EnableJpaRepositories(basePackages = "com.xxx")
@PropertySources(value = {@PropertySource("classpath:desktop.properties")})
@EnableAutoConfiguration(exclude={JmsAutoConfiguration.class, SecurityAutoConfiguration.class, MultipartAutoConfiguration.class})
@ImportResource(value = {"classpath:multipart.xml","classpath:column-maps-config.xml","classpath:model-ui-name-maps-config.xml"})
public class ApplicationConfig extends WebMvcConfigurerAdapter implements EnvironmentAware, WebApplicationInitializer {
}

This class imports desktop.properties as you can notice.

And I have a test class that starts with:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = ApplicationConfig.class)
@WebAppConfiguration
public class SomeControllerTest {
}

If I my environment doesn't have the desktop.properties file or I simply delete it then tests couldn't be run because ApplicationConfig class can't be instantiated without the dependency.

My question is how can I mock desktop.properties or create a custom configuration for test purposes in order to replace @ContextConfiguration(classes = ApplicationConfig.class) with my test context?

Could you be so kind to give me any hints about it?

P.S. the current project is a quite old one with old versions so this is only one way I found to create tests for controllers with minimum changes to pom.xml

3 Answers

The @TestPropertySource annotation is the simplest way to configure property source in Spring integration tests.

You could try this test anotations:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = ApplicationConfig.class)
@ActiveProfiles("test")
@WebAppConfiguration
public class SomeControllerTest {
}

Next you have to create specific test desktop.properties in /src/test/resources

You can create a different configuration class for test environment and use it in your test. This test application config class will not have the statement -

@PropertySourcesl(value = {
@PropertySource("classpath:desktop.propertie s ")})

And wherever you are using some of the properties from the above file, use some default values so that it won't fail with any runtime exception.

Related