简单的Springboot Junittest失败,没有支持的数据源类型

发布于 2025-02-09 11:56:42 字数 9222 浏览 1 评论 0原文

我对我的sprinboot应用程序有一个非常简单的junit测试:

@springboottest(class = {application.class}) 公共类TestContext {
@测试 void ContextLoads(ApplicationContext上下文) { assertnotnull(上下文); } }

和一个使用两个DBS的非常简单的应用程序:

@SpringBootApplication
@EnableAutoConfiguration
public class Application
{
  private static final Logger applogger = LoggerFactory.getLogger("Application"); 

  @Autowired
  private DbSource userSource;
  @Autowired
  private DbSource dataSource;


  public static void main(String[] args) 
  {   
   SpringApplication.run(Application.class, args);   
  }
}

尽管应用程序有效,但我无法进行单元测试运行。返回的错误是:

Failed to load ApplicationContext java.lang.IllegalStateException
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'application': Unsatisfied dependency expressed through field 'userSource'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userSource' defined in class path resource [it/unict/spring/application/configurations/DbSourceConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [it.unict.spring.application.data.DbSource]: Factory method 'getUserSource' threw exception; nested exception is java.lang.IllegalStateException: No supported DataSource type found
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userSource' defined in class path resource [it/unict/spring/application/configurations/DbSourceConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [it.unict.spring.application.data.DbSource]: Factory method 'getUserSource' threw exception; nested exception is java.lang.IllegalStateException: No supported DataSource type found
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [it.unict.spring.application.data.DbSource]: Factory method 'getUserSource' threw exception; nested exception is java.lang.IllegalStateException: No supported DataSource type found
Caused by: java.lang.IllegalStateException: No supported DataSource type found

请注意,我将扩展测试,以检查是否存储了正确的DB架构。

更新:

我将@ContextConfiguration添加到单元测试:

@SpringBootTest
@ContextConfiguration(classes={DbSourceConfig.class, DbSource.class})
public class TestContext
 { 
  @Test
  void contextLoads(ApplicationContext context)
   {
   assertNotNull(context);       
   }
 }

现在错误是:

Failed to load ApplicationContext java.lang.IllegalStateException
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'dbSource': Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'java.lang.String' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'java.lang.String' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}

POM是:

<?xml version="1.0" encoding="UTF-8"?>
 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.7.1-SNAPSHOT</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>
    
<groupId>it.unict.spring</groupId>
<artifactId>SpringApplication</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>SpringApplication</name>        
<description>Demo project for Spring Boot</description>
<properties>
    <java.version>1.8</java.version>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
            <start-class>controllers.Application</start-class>
</properties>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>         
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>   
            <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-test</artifactId>                        
        <scope>test</scope>
    </dependency>               
                            
            <dependency>
                <groupId>org.mariadb.jdbc</groupId>
                <artifactId> mariadb-java-client</artifactId>
            </dependency>
            
        
            
</dependencies>

<build>
            <finalName>SpringApplication</finalName>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>
<repositories>
    <repository>
        <id>spring-milestones</id>
        <name>Spring Milestones</name>
        <url>https://repo.spring.io/milestone</url>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
    </repository>
    <repository>
        <id>spring-snapshots</id>
        <name>Spring Snapshots</name>
        <url>https://repo.spring.io/snapshot</url>
        <releases>
            <enabled>false</enabled>
        </releases>
    </repository>
</repositories>
<pluginRepositories>
    <pluginRepository>
        <id>spring-milestones</id>
        <name>Spring Milestones</name>
        <url>https://repo.spring.io/milestone</url>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
    </pluginRepository>
    <pluginRepository>
        <id>spring-snapshots</id>
        <name>Spring Snapshots</name>
        <url>https://repo.spring.io/snapshot</url>
        <releases>
            <enabled>false</enabled>
        </releases>
    </pluginRepository>
</pluginRepositories>

application.properties文件:

spring.datasource.url=jdbc:mariadb://localhost:3306/data
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=org.mariadb.jdbc.Driver


spring.datasource2.url=jdbc:mariadb://localhost:3306/users
spring.datasource2.username=root
spring.datasource2.password=root
spring.datasource2.driver-class-name=org.mariadb.jdbc.Driver

spring.jpa.hibernate.ddl-auto=validate

dbsourceconfig文件:

import it.unict.spring.application.data.DbSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


@Configuration
public class DbSourceConfig
{
  
 @Value("${spring.datasource.url}")                   
 private String urlUser;
 @Value("${spring.datasource2.url}") 
 private  String urlData;
 @Value("${spring.datasource.username}") 
 private  String username;
 @Value("${spring.datasource.password}") 
 private  String password;    

 @Bean(name="userSource")
 public DbSource getUserSource()
  {
   return new DbSource(urlUser, username, password);
  }

@Bean(name="dataSource")
public DbSource getDataSource()
{
 return new DbSource(urlData, username, password);
}      

}

servletinitializer文件:

import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;

public class ServletInitializer extends SpringBootServletInitializer {

@Override
public SpringApplicationBuilder configure(SpringApplicationBuilder application)
    {
    return application.sources(Application.class);                
   }
  }

I have a very simple JUnit test for my Sprinboot app:

@SpringBootTest(classes={Application.class})
public class TestContext
{
@Test
void contextLoads(ApplicationContext context)
{
assertNotNull(context);
}
}

And a very simple application which uses two Dbs:

@SpringBootApplication
@EnableAutoConfiguration
public class Application
{
  private static final Logger applogger = LoggerFactory.getLogger("Application"); 

  @Autowired
  private DbSource userSource;
  @Autowired
  private DbSource dataSource;


  public static void main(String[] args) 
  {   
   SpringApplication.run(Application.class, args);   
  }
}

Despite the application works, I cannot make the unit test run. The error returned is:

Failed to load ApplicationContext java.lang.IllegalStateException
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'application': Unsatisfied dependency expressed through field 'userSource'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userSource' defined in class path resource [it/unict/spring/application/configurations/DbSourceConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [it.unict.spring.application.data.DbSource]: Factory method 'getUserSource' threw exception; nested exception is java.lang.IllegalStateException: No supported DataSource type found
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userSource' defined in class path resource [it/unict/spring/application/configurations/DbSourceConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [it.unict.spring.application.data.DbSource]: Factory method 'getUserSource' threw exception; nested exception is java.lang.IllegalStateException: No supported DataSource type found
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [it.unict.spring.application.data.DbSource]: Factory method 'getUserSource' threw exception; nested exception is java.lang.IllegalStateException: No supported DataSource type found
Caused by: java.lang.IllegalStateException: No supported DataSource type found

Notice that I would extend the test in order to check that the correct DB Schema are stored.

Update:

I added @ContextConfiguration to unit test:

@SpringBootTest
@ContextConfiguration(classes={DbSourceConfig.class, DbSource.class})
public class TestContext
 { 
  @Test
  void contextLoads(ApplicationContext context)
   {
   assertNotNull(context);       
   }
 }

Now the error is:

Failed to load ApplicationContext java.lang.IllegalStateException
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'dbSource': Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'java.lang.String' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'java.lang.String' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}

The POM is:

<?xml version="1.0" encoding="UTF-8"?>
 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.7.1-SNAPSHOT</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>
    
<groupId>it.unict.spring</groupId>
<artifactId>SpringApplication</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>SpringApplication</name>        
<description>Demo project for Spring Boot</description>
<properties>
    <java.version>1.8</java.version>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
            <start-class>controllers.Application</start-class>
</properties>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>         
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>   
            <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-test</artifactId>                        
        <scope>test</scope>
    </dependency>               
                            
            <dependency>
                <groupId>org.mariadb.jdbc</groupId>
                <artifactId> mariadb-java-client</artifactId>
            </dependency>
            
        
            
</dependencies>

<build>
            <finalName>SpringApplication</finalName>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>
<repositories>
    <repository>
        <id>spring-milestones</id>
        <name>Spring Milestones</name>
        <url>https://repo.spring.io/milestone</url>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
    </repository>
    <repository>
        <id>spring-snapshots</id>
        <name>Spring Snapshots</name>
        <url>https://repo.spring.io/snapshot</url>
        <releases>
            <enabled>false</enabled>
        </releases>
    </repository>
</repositories>
<pluginRepositories>
    <pluginRepository>
        <id>spring-milestones</id>
        <name>Spring Milestones</name>
        <url>https://repo.spring.io/milestone</url>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
    </pluginRepository>
    <pluginRepository>
        <id>spring-snapshots</id>
        <name>Spring Snapshots</name>
        <url>https://repo.spring.io/snapshot</url>
        <releases>
            <enabled>false</enabled>
        </releases>
    </pluginRepository>
</pluginRepositories>

The application.properties file:

spring.datasource.url=jdbc:mariadb://localhost:3306/data
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=org.mariadb.jdbc.Driver


spring.datasource2.url=jdbc:mariadb://localhost:3306/users
spring.datasource2.username=root
spring.datasource2.password=root
spring.datasource2.driver-class-name=org.mariadb.jdbc.Driver

spring.jpa.hibernate.ddl-auto=validate

The DbSourceConfig file:

import it.unict.spring.application.data.DbSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


@Configuration
public class DbSourceConfig
{
  
 @Value("${spring.datasource.url}")                   
 private String urlUser;
 @Value("${spring.datasource2.url}") 
 private  String urlData;
 @Value("${spring.datasource.username}") 
 private  String username;
 @Value("${spring.datasource.password}") 
 private  String password;    

 @Bean(name="userSource")
 public DbSource getUserSource()
  {
   return new DbSource(urlUser, username, password);
  }

@Bean(name="dataSource")
public DbSource getDataSource()
{
 return new DbSource(urlData, username, password);
}      

}

The ServletInitializer file:

import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;

public class ServletInitializer extends SpringBootServletInitializer {

@Override
public SpringApplicationBuilder configure(SpringApplicationBuilder application)
    {
    return application.sources(Application.class);                
   }
  }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

烂柯人 2025-02-16 11:56:42

junit需要Spring-Boot-Starter-JDBC,而POM.xml缺少。添加依赖性解决了问题

spring-boot-starter-jdbc is required by junit and missing from the pom.xml. Adding the dependecy resolved the issue

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文