gpt4 book ai didi

spring-boot - 在 Spring Boot 测试中为组件扫描配置基础包

转载 作者:行者123 更新时间:2023-12-03 12:24:19 25 4
gpt4 key购买 nike

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

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 {
...
}

服务1 将被注入(inject)。但是 服务2 不会,因为它与测试类不在同一个包中。我收到一个错误:

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



如何告诉我的测试上下文我想加载/扫描某个包,例如 com.hello ?

最佳答案

很高兴在上面添加测试配置我在测试配置和任何测试用例中有以下内容。我是 Spring 启动测试的新手,但它可以工作。让我知道,如果我错了。

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

关于spring-boot - 在 Spring Boot 测试中为组件扫描配置基础包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48747421/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com