为什么我不能直接在我的测试中@Autowired我的服务,为什么我需要@Autowired存储库?

问题描述 投票:0回答:1

我有一个Repository的春季启动应用程序。

我也使用@Service并在其中扩展repository

当我尝试@Autowired我所拥有的服务时:

引起:org.springframework.beans.factory.NoSuchBeanDefinitionException:没有'com.api.core.service.CountryService'类型的限定bean可用:预期至少有1个bean可以作为autowire候选者。依赖注释:{@ 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.**";

}
java spring hibernate spring-mvc
1个回答
1
投票

基于您发布的代码,您可能需要在一个测试上下文类com.api.core.service.CountryServiceUserManagementConfig中对UserManagementServiceConfig Bean进行组件扫描

@ComponentScan({
     basePackages = {"com.api.core.service"}
})

要测试app上下文是否加载了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})
© www.soinside.com 2019 - 2024. All rights reserved.