Jordi
Jordi

Reputation: 23187

Spring test: Avoid to load configuration class on test

This is a Spring @Configuration annotated class I'm using into my spring boot project:

@Configuration
@ImportResource({ 
    "classpath:cat/gencat/ctti/canigo/arch/web/rs/config/canigo-web-rs.xml",
    "classpath:cat/gencat/ctti/canigo/arch/core/i18n/config/canigo-core-i18n.xml"
})
public class WebServicesConfiguration {

As you can see I'm importing third-party declared resources.

Nevertheless, I'm trying to avoid to import them into my tests. Currently, I'm trying to create tests in order to test database communication. I don't need to load those resources.

How could I get it?

Here's my related code snippet:

@RunWith(SpringRunner.class)
@SpringBootTest()
public class ModelTest {

    @Autowired
    private MongoTemplate mongoTemplate;

So, I want to avoid to load WebServicesConfiguration configuration class when ModelTest runs.

Any ideas?

Upvotes: 5

Views: 2179

Answers (2)

user10367961
user10367961

Reputation:

You could use Spring Profiles to implement your scenario.

First of all, add a profile annotation to your configurations. Note that you could add multiple profiles to a single configuration (as in the snipped below), and the configuration will be applied if any of the specified profiles is active.

@Configuration
@ImportResource({ 
    "classpath:cat/gencat/ctti/canigo/arch/web/rs/config/canigo-web-rs.xml",
    "classpath:cat/gencat/ctti/canigo/arch/core/i18n/config/canigo-core-i18n.xml"
})
@Profile(value = {"dev", "prod"})
public class WebServicesConfiguration {

}

Then, on your test side, define which profiles you want active for the test.

@RunWith(SpringRunner.class)
@SpringBootTest() 
@ActiveProfiles(profiles = {"test"})
public class ModelTest {

    @Autowired
    private MongoTemplate mongoTemplate;

}

Upvotes: 3

Alexander Petrov
Alexander Petrov

Reputation: 991

You could create a separate configuration for all tests and named it ApplicationTest. In your tests you need to specify it by using the following code:

@SpringBootTest(classes = ApplicationTest.class)
public class ModelTest {

    @Autowired
    private MongoTemplate mongoTemplate;
}

Upvotes: 1

Related Questions