当前位置: 首页 > 知识库问答 >
问题:

SpringBoot测试类不会注入bean

柳刚豪
2023-03-14

我正在使用以下依赖项:

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'spring-boot'
apply plugin: 'war'

 compile("com.caucho:resin-hessian:4.0.23")
    compile("mysql:mysql-connector-java")
    compile('org.springframework.boot:spring-boot-starter-web:1.2.0.RELEASE')
    compile("org.springframework.boot:spring-boot-starter-batch:1.2.0.RELEASE")
    compile("org.springframework.boot:spring-boot-starter-actuator")
    compile("javax.inject:javax.inject:1")
    compile('org.springframework.batch:spring-batch-admin-manager:1.3.0.RELEASE') {
        exclude module: 'slf4j-log4j12'
    }
    //SI
    compile("org.springframework.integration:spring-integration-core:$springIntegrationVersion")
    testCompile('org.springframework.boot:spring-boot-starter-test:1.2.0.RELEASE')

创建了新的测试类:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebAppConfiguration
@IntegrationTest
@ContextConfiguration(locations={"classpath:**/*.xml"})
@ComponentScan({"com.mycompany.notification.processor.service"})
public class DownloadFileTaskletTest  {

    @Autowired
     private DownloadFileTasklet downloadFileTasklet;

    @Test
    public void execute()
    {
        System.out.printf("test123");

    }
}

我在Spring Boot中创建了测试用例,但是我得到了这个错误:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'batch.DownloadFileTaskletTest': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.mycompany.notification.processor.service.batch.tasks.DownloadFileTasklet batch.DownloadFileTaskletTest.downloadFileTasklet; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.mycompany.notification.processor.service.batch.tasks.DownloadFileTasklet] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

这是我的应用程序类:

@ComponentScan({"com.mycompany.notification.processor.service"})
@EnableAutoConfiguration
@Configuration
@ImportResource({
        "classpath:integration-context.xml","classpath:launch-context.xml","classpath:applicationContext-NotificationProcessorService.xml"
})
//@Import({ ServletConfiguration.class, WebappConfiguration.class })
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
        System.out.printf("hello man");
    }

}

知道我为什么不能在测试类中注入bean吗?

我按照建议删除了@ContextConfiguration,@ComponentScan,@ConnecationTes现在我看到了不同的异常:

java.lang.IllegalStateException: Failed to load ApplicationContext
    at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:99)
    at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:122)
    at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:160)
    at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:101)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:321)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:211)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:288)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:284)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:88)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:157)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:74)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:211)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:67)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
Caused by: java.lang.IllegalArgumentException: Cannot load an ApplicationContext with a NULL 'contextLoader'. Consider annotating your test class with @ContextConfiguration or @ContextHierarchy.
    at org.springframework.util.Assert.notNull(Assert.java:112)
    at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContextInternal(CacheAwareContextLoaderDelegate.java:57)
    at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:91)
    ... 28 more

共有1个答案

全鸿晖
2023-03-14

只要去掉这部分:

<dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-test</artifactId>
   <version>3.2.13.RELEASE</version>
</dependency>

相反,使用这个:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
 类似资料:
  • 问题内容: 我使用SpringBeanAutowiringSupport在某些对象中进行bean注入。问题是,在jUnit测试中无法注入bean。为了进行测试,使用了SpringJUnit4ClassRunner。 有谁知道,为什么使用注入在jUnit测试中不起作用? 问题答案: 感谢M. Denium的帮助,他的解决方案得以奏效。

  • 我有一个集成测试来测试Spring Boot服务器的其余endpoint。 我需要创建一些数据(不使用RESTendpoint),所以我尝试使用TestEntityManager,所以我用@SpringBootTest注释了我的测试类。到目前为止还不错,测试启动了Spring Boot上下文,因此我的服务器和测试通过了。 问题:我需要在这个集成测试之外启动Spring Boot服务器,以便为所有集

  • 我想配置一个Spring Boot应用程序,以便根本不使用DB。因此,我对应用程序类进行了注释,以排除JPA自动配置类: 原因:org.springframework.beans.factory.BeanCreationException:创建名为“data source”的bean时出错:调用init方法失败;嵌套异常是java.lang.IllegalStateException:无法为测试确

  • Summary NoSQL databases provide looser consistency restrictions than traditional SQL databases. By requiring fewer relational constraints and consistency checks, NoSQL databases often offer performanc

  • Summary In this section, some SQL Injection techniques for PostgreSQL will be discussed. These techniques have the following characteristics: PHP Connector allows multiple statements to be executed by

  • Summary SQL Injection vulnerabilities occur whenever input is used in the construction of a SQL query without being adequately constrained or sanitized. The use of dynamic SQL (the construction of SQL