3

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

Pasha
  • 1,768
  • 6
  • 22
  • 43
  • if having as little version changes as possible is an important constraint for you then mentioning what these versions are seems substantial to be able to answer your question. – jannis Oct 22 '18 at 16:02

3 Answers3

4

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

Sam Brannen
  • 29,611
  • 5
  • 104
  • 136
  • This answer really seems like the most fitting response to the given question. The name of the annotation says it all! – Blake Oct 23 '18 at 13:58
1

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

leon cio
  • 366
  • 4
  • 11
0

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.

Rahul Vedpathak
  • 1,346
  • 3
  • 16
  • 30