Configuring base package for component scan in Spring boot test

ElArbi picture ElArbi · Feb 12, 2018 · Viewed 16.1k times · Source

When I launch my test with the following annotations:

package com.hello.package.p1;

@RunWith(SpringRunner.class)
@DataMongoTest
@SpringBootTest
public class ClassATest {

@Autowired
Service1 serivce1; //fqn = com.hello.package.p1.Service1 

@Autowired
Service2 serivce2; //fqn = com.hello.package.p2.Service2 

...}

package com.hello.package.p1;

@ActiveProfiles("test")
@SpringBootConfiguration
public class MongoTestConfig {
...
}

service1 will be injected. But service2 will not, since it is not in the same package as the test class. I get an error:

Unsatisfied dependency expressed through field 'service2'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException

How can I tell my testing context that I want to load/scan a certain package, for example com.hello?

Answer

Ortomala Lokni picture Ortomala Lokni · Feb 15, 2019

You can add a TestConfig class in your test package:

@Configuration
@ComponentScan({ "com.hello.package.p1", "com.hello.package.p2" })
public class TestConfig {
}