【问题标题】:Configuring base package for component scan in Spring boot test在 Spring Boot 测试中为组件扫描配置基础包
【发布时间】:2018-07-22 16:17:35
【问题描述】:

当我使用以下注释启动我的 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

【问题讨论】:

  • 您也可以添加您的主要SpringBootApplication 吗?您可以将ComponentScan 添加到测试并指定,但理想情况下您应该让SpringBootApplication 为您完成。此外,您正在混合切片测试和完整启动测试,在大多数情况下您应该选择其中一个。
  • @DarrenForsythe 我已经添加了@ComponentScan(basePackages = {"com.hello.package.p1", "com.hello.package.p2"}) 并且有效!谢谢!

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


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    很好地添加上面的测试配置我在测试配置和任何测试用例中有以下内容。我是春季启动测试的新手,但它可以工作。如果我错了,请告诉我。

        @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"));
            }
        }
    

    【讨论】:

    • 你正在通过 @TestPropertySource 加载 application.yml,听起来不对
    • 那你有什么建议?
    猜你喜欢
    • 1970-01-01
    • 2015-01-13
    • 2019-01-11
    • 2018-07-18
    • 1970-01-01
    • 2019-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多