我有Springboot应用程序可以很好地连接到Datasource。对于Junit,我已经禁用了DataSource的自动配置,方法是排除DatasourceAutoConfiguration、DataSourceTransactionManagerConfiguration、HibernateJpaAutoConfiguration类,以避免SpringBoot自动配置DataSource。
pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<version>2.2.5.RELEASE</version>
<dependency>
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>8.2.2.jre8</version>
<dependency>主班
@SpringBootApplication
@EnableAutoConfiguration
@ComponentScan({"com.basepackage"})
public class SampleClass{
psvm(){
SpringApplication.run(SampleClass.class,args);
}
}JuniTestClass
@RunWith(SpringRunner.class)
@SpringBootTest(classes=SampleClass.class)
@AutoConfigureMockMvc
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class, DataSourceTransactionManagerConfiguration.class, HibernateJpaAutoConfiguration.class})
public class SampleControllerTest {
@MockBean
private SampleService service;
@Test
public void fetchUsers() {
Mockito.when(service.retrieveUsers().thenReturn(new SampleResponse());
}}
在mvn测试中,测试脚本会运行但失败,因为Springboot没有自动配置SampleRepository bean (可能是因为删除了Datasource和HibernateJpa自动配置类)
错误
Caused by UnsatisfiedDependencyException: Error creating bean with name ServiceDAOImpl, nested exception No qualifying bean of type com.basepackage.repository.SampleRepository' : expected atleast 1 bean which qualifies ...................如果删除AutoConfig排除,Junit测试在配置Datasource的本地工作区中工作正常(尽管不应该建立到DB的JUnit连接)。问题是,我正在设置devops管道,在"Maven测试“期间,SpringBoot自动配置DataSource,而到Jenkins到DB的连接失败。
我想在Junit - Maven测试期间禁用Autoconfig,在实际的SpringBoot jar构建中,应该启用自动配置。
有人能告诉我如何通过注释来实现这一点吗?
发布于 2020-06-29 07:32:01
禁用数据库的自动配置是一回事,但是应用程序类依赖于(我猜) Spring中的JPA存储库(它们使用@Autowired注入)来工作。
如果您现在禁用了数据库的自动配置,那么您的JPA存储库就不能被Spring引导,因此您的服务类在启动时就会失败,因为它们需要一个可用的实例:... expected at least 1 bean which qualifies。
我想你有三个选择来解决这个问题:
@SpringBootTest
class ApplicationIntegrationTest {
@TestConfiguration
public static class TestConfig {
@Bean
public DataSource dataSource() {
return DataSourceBuilder
.create()
.password("YOUR PASSWORD")
.url("YOUR MSSQL URL")
.username("YOUR USERNAME")
.build();
}
}
}@MockBean。这将允许您在没有任何数据库的情况下完成工作,但您必须使用Mockito为自己定义与存储库的任何交互:@SpringBootTest
class SpringBootStackoverflowApplicationTests {
@MockBean
private SampleRepository sampleRepository;
@MockBean
private OtherRepository otherRepository;
// your tests
}https://stackoverflow.com/questions/62609532
复制相似问题