相关疑难解决方法(0)

@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);

  }
}
Run Code Online (Sandbox Code Playgroud)

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

@Autowired
private OtherSampleClass sampleBean;
Run Code Online (Sandbox Code Playgroud)

在我的“OtherSampleClass”中,我注释了一个方法,如下所示:

@Bean(name = "sampleBean")
public void someMethod(){
....
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

我已经使用Spring Boot 测试文档来帮助我解决这个问题。

java unit-testing spring-boot

17
推荐指数
2
解决办法
3万
查看次数

在源树中运行所有测试,而不是包

我的单元测试位于与集成测试不同的目录树中,但具有相同的包结构.我的集成测试需要外部资源(例如服务器),但我的单元测试正确地相互独立和环境.

在IntelliJ-IDEA(v7)中,我定义了一个JUnit运行/调试配置来运行顶级包中的所有测试,这当然会选择失败的集成测试.

我想定义一个运行所有单元测试的run-junit配置.有任何想法吗?

java junit unit-testing intellij-idea

5
推荐指数
2
解决办法
2554
查看次数

@Autowired 和 @SpringBootTest 应该在单元测试中使用吗?

在我工作的一个项目中,我们一直通过以下方式初始化单元测试服务:

  1. 模拟服务所需的依赖项。
  2. 使用构造函数创建服务。

像这样的东西:

@RunWith(SpringRunner.class)
public class ServiceTest extends AbstractUnitTest {

  @Mock private Repository repository;
  private Service service;

  @Before
  public void init() {
    service = new Service(repository);
    when(repository.findById(any(Long.class))).thenReturn(Optional.of(new Entity()));
  }
}
Run Code Online (Sandbox Code Playgroud)

但我们的新开发人员建议使用@Autowired@SpringBootTest

@SpringBootTest(classes = ServiceTest.class)
@MockBean(classes = Repository.class)
@RunWith(SpringRunner.class)
public class ServiceTest extends AbstractUnitTest {

  @MockBean private Repository repository;
  @Autowired private Service service;

  @Before
  public void init() {
    when(repository.findById(any(Long.class))).thenReturn(Optional.of(new Entity()));
  }
}
Run Code Online (Sandbox Code Playgroud)

在此之前,我认为@Autowiredand@SpringBootTest应该仅在集成测试中使用。但谷歌搜索了很多,我发现有些人在单元测试中使用这两个。我读了boot-features-testing。另外,我阅读了单元测试与 Spring 集成测试。对我来说,我们仍然感觉不太好,因为我们可以自己做单元测试,所以需要让 Spring 来进行单元测试的依赖注入。那么,应该 在单元测试中使用@Autowired …

java spring unit-testing spring-boot

4
推荐指数
1
解决办法
2488
查看次数

标签 统计

java ×3

unit-testing ×3

spring-boot ×2

intellij-idea ×1

junit ×1

spring ×1