@Autowired Bean 在 Spring Boot 单元测试中为 NULL

新手上路,请多包涵

我是 JUnit 和自动化测试的新手,真的很想自动化我的测试。这是一个 Spring Boot 应用程序。我使用基于 Java 的注释样式而不是基于 XML 的配置。

我有一个测试类,我想在其中测试一种根据用户输入检索响应的方法。

测试类:

 @RunWith(SpringRunner.class)
@SpringBootTest
public class SampleTest(){

  @Autowired
  private SampleClass sampleClass;

  @Test
  public void testInput(){

  String sampleInput = "hi";

  String actualResponse = sampleClass.retrieveResponse(sampleInput);

  assertEquals("You typed hi", actualResponse);

  }
}

在我的“SampleClass”中,我已经像这样自动装配了一个 bean。

 @Autowired
private OtherSampleClass sampleBean;

在我的“OtherSampleClass”中,我注释了这样一个方法:

 @Bean(name = "sampleBean")
public void someMethod(){
....
}

我遇到的问题是,当我尝试在没有 @RunWith@SpringBootTest 注释的情况下运行测试时,当我尝试运行测试我的变量注释时 @Autowired 无效的。当我尝试使用这些注释运行测试时 RunWith & SpringBootTest 然后我得到一个

BeanCreationException 引起的 IllegalStateException:创建名称为“sampleBean”的 bean 时出错,加载应用程序上下文失败由 BeanInstantiationException 引起。

当我尝试像用户一样使用它时,代码“正常”工作,所以我总是可以通过这种方式进行测试,但我认为自动化测试对程序的寿命有好处。

我已经使用 Spring Boot 测试文档 来帮助我完成这项工作。

原文由 alwaysStuckJava 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 760
1 个回答

以下配置对我有用。

文件: build.gradle

 testCompile("junit:junit:4.12")
testCompile("org.springframework.boot:spring-boot-starter-test")

文件: MYServiceTest.java

 import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;

@SpringBootTest(classes = Application.class,
    webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ActiveProfiles("test")
@RunWith(SpringRunner.class)
public class MYServiceTest {

    @Autowired
    private MYService myService;

    @Test
    public void test_method() {
        myService.run();
    }
}

原文由 Eddy 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题