Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock property source in spring test?

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

like image 696
Pasha Avatar asked Oct 27 '25 08:10

Pasha


2 Answers

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

like image 50
Sam Brannen Avatar answered Oct 28 '25 21:10

Sam Brannen


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

like image 30
leon cio Avatar answered Oct 28 '25 22:10

leon cio



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!