在Spring启动测试中为组件扫描配置基础包

时间:2018-02-12 13:17:12

标签: spring-boot spring-data spring-test

当我使用以下注释启动 test 时:

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 。但 service2 不会,因为它与测试类不在同一个包中。我收到一个错误:

  

通过字段'service2'表示的不满意的依赖;嵌套   例外是   org.springframework.beans.factory.NoSuchBeanDefinitionException

如何告诉我的测试环境我想要加载/扫描某个包,例如com.hello

3 个答案:

答案 0 :(得分:1)

您可以在测试包中添加TestConfig类:

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

答案 1 :(得分:0)

也在 IntelliJ 中为我工作:

-右键单击测试文件夹>将目录标记为测试源

enter image description here

答案 2 :(得分:0)

很好地在上面添加测试配置我在测试配置和任何测试用例中都有以下内容。我是Spring Boot测试的新手,但可以。让我知道,如果我错了。

    @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"));
        }
    }
相关问题