我有一个带有存储库
的 Spring Boot 应用程序。
我还使用@Service
并扩展其中的存储库
。
当我尝试 @Autowired 我拥有的服务时:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.api.core.service.CountryService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
如果我@Autowired
存储库,它就可以正常工作。
我的测试必须如下所示:
@SpringBootTest
@ActiveProfiles("core")
@ContextConfiguration(classes = { UserManagementConfig.class, UserManagementServiceConfig.class })
@UserManagementTx
@RunWith(SpringRunner.class)
public class BlogPostContentImplTest {
@Autowired
private CountryService countryService;
@Autowired
private BlogPostContentRepository blogPostContentRepository;
private BlogPostContentServiceImpl blogPostContentService;
private BlogPostContent entity = new BlogPostContent();
@Before
public void setUp() throws Exception {
blogPostContentService = new BlogPostContentServiceImpl(blogPostContentRepository);
List<Country> countryList = countryService.findAll(null);
entity = new BlogPostContent();
entity.setId(1L);
entity.setDescription("test");
entity.setCountry(countryList.get(0));
blogPostContentService.insert(entity);
}
@After
public void tearDown() throws Exception {
blogPostContentService.delete(entity.getId());
}
@Test
public void findAll() throws Exception {
assertThat(blogPostContentService.findAll(null).size()).isGreaterThan(0);
}
}
这就是我配置上下文的方式:
@Configuration
@ComponentScan({
UserManagementConfig.CONTEXT_CLASSPATH
})
public class UserManagementConfig {
public static final String CONTEXT_CLASSPATH = "com.api.userManagement.config.context.**";
}
@Configuration
@ComponentScan({
UserManagementServiceConfig.CLASSPATH,
})
public class UserManagementServiceConfig {
public static final String CLASSPATH = "com.api.userManagement.service.**";
}
最佳答案
根据您发布的代码,您似乎可能需要在测试上下文类之一中对 com.api.core.service.CountryService
Bean 进行组件扫描 UserManagementConfig
或 UserManagementServiceConfig
@ComponentScan({
basePackages = {"com.api.core.service"}
})
<小时/>
要测试应用程序上下文是否加载您的 bean,您可以创建一个 TestContext
类,如下所示
@Configuration
@ComponentScan(basePackages = "com.api.core.service")
public class TestContext implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(TestContext.class, args);
}
}
在您的测试中配置TestContext
,如下所示
@ContextConfiguration(classes = {TestContext.class})
关于java - 为什么我不能直接在测试中 @Autowired 我的服务以及为什么我需要 @Autowired 存储库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47842680/