小编Son*_*nka的帖子

@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 ×1

spring ×1

spring-boot ×1

unit-testing ×1