30

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?

AlexTa
  • 5,133
  • 3
  • 29
  • 46
ElArbi
  • 1,145
  • 3
  • 13
  • 22
  • 1
    Can you add your main `SpringBootApplication` too please? You can just add `ComponentScan` to the test and specify, but ideally you should just have the `SpringBootApplication` do it for you. Additionally you're mixing a slice test and a full boot test, you should pick one or the other in most situations. – Darren Forsythe Feb 12 '18 at 14:50
  • @DarrenForsythe I've added @ComponentScan(basePackages = {"com.hello.package.p1", "com.hello.package.p2"}) and it worked ! THANKS ! – ElArbi Feb 12 '18 at 15:21

2 Answers2

21

You can add a TestConfig class in your test package:

@Configuration
@ComponentScan({ "com.hello.package.p1", "com.hello.package.p2" })
public class TestConfig {
}
Ortomala Lokni
  • 56,620
  • 24
  • 188
  • 240
19

Good to add the test config above I have the following in test config and any test case. I am new to spring boot test but it work. Let me know, if I am wrong.

    @Configuration
    @ComponentScan("au.some.spring.package")
    public class TestConfig {
    }
    @RunWith(SpringRunner.class)
    @EnableAutoConfiguration
    @SpringBootTest(classes= TestConfig.class)
    @TestPropertySource({"classpath:application.yml", 
    "classpath:env-${testing.env}.properties"})
    public class DBDmoTest {

        @Autowired
        PartyRepository partyRepository;
        @Test
        public void test(){
            Assert.assertNull(partyRepository.findByEmailIgnoreCase("some@abc.com"));
        }
    }
user2560347
  • 301
  • 2
  • 3