在我工作的项目中,我们一直在通过以下方式初始化单元测试服务:
- 模拟服务所需的依赖项。
- 使用构造函数创建服务。
像这样:
@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()));
}
}
但是我们的新开发人员建议使用@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()));
}
}
在此之前,我认为@Autowired
和@SpringBootTest
应该只用于集成测试。但是在谷歌上搜索了很多,我看到有些人在单元测试中使用这两个。
我读了boot-features-testing .另外,我读了这个 Unit tests vs integration tests with Spring .
对我来说,我们需要让Spring来做单元测试的依赖注入(inject)还是不太好,因为我们可以自己做单元测试。
那么,@Autowired
和@SpringBootTest
是否应该用于单元测试呢?
最佳答案
没有。 单元 测试是单独测试单个组件。在 bean 中使用构造函数注入(inject)允许您非常简单地调用 new SomeService(myMock)
,不需要 Spring。
编写组件或功能测试(测试您的应用程序但不将其连接到外部服务以进行完整的集成测试,仅模拟外部接口(interface);这对事情有好处像 MockMvc 测试)非常适合 @SpringBootTest
,在这种情况下,您可能需要在 Spring 配置中创建模拟对象并将它们 Autowiring 到您的测试中,以便您可以操作它们。
关于java - @Autowired 和@SpringBootTest 应该用于单元测试吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58192035/