lundi 10 avril 2017

Testing Spring app with @ActiveProfiles and appropriate property files

I have this class that I want to test:

@Service
public class MyService {

    @Value("${property1}")
    private String property1;

    ...
}

src/main/resources contains application.properties and application-int.properties which contain a different value for property1.

The test class:

@RunWith(SpringJUnit4ClassRunner.class)
@ActiveProfiles("int")
@ContextConfiguration(classes = {IntegrationTestingConfiguration.class})
public class MyServiceIT {

    @Autowired
    MyService myService;

    @Test
    public void test() {
    ...
    }
}

And IntegrationTestingConfiguration

@Configuration
@ConfigurationProperties
@ComponentScan(
    useDefaultFilters = false,
    basePackageClasses = com.xxx.MyService.class,
includeFilters = {
    @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = com.xxx.MyService.class)
})
public class IntegrationTestingConfiguration {
}

The problem is property1 in MyService never gets populated.
I tried to use @SpringApplicationConfiguration, @TestPropertySource(locations = "classpath:application-int.properties") and other annotations but it doesn't work.

What is the correct and simplest way to automatically load and bind configuration properties in a test according to an active profile?

Aucun commentaire:

Enregistrer un commentaire