我有一个服务层和一个领域层。我为域层使用普通的原生 Spring 存储库,在我的测试设置中,我使用 dbunit
模拟数据库。
@Repository
public interface ExampleRepository extends PagingAndSortingRepository<ExampleEntity, Long>, JpaSpecificationExecutor<ExampleEntity> {
}
自然地,我会假设 Spring 存储库实现没有错误,因此领域层不受测试。
我对单元测试的一般了解是,在为我的服务层编写单元测试时,我需要模拟我的领域层。
我假设领域层不需要测试,而且我使用 dbunit
来模拟我的数据库,我是否可以使用此设置进行单元测试我的服务层?
最佳答案
如果我理解正确的话,在你的测试中,Spring 上下文被引导,你的服务层与你的域层一起被测试,并且数据使用 DBUnit 插入到你的测试数据库中。
有了这个,让我们开始:
My general knowledge about unit testing is that I would need to mock my domain layer when writing unit tests for my service layer.
如果你想做一个单元测试,那么这是正确的。您描述测试的方式取决于两个层是否正确,并且数据库必须运行,因此,根据定义,它们是集成测试。
With my assumption that the domain layer does not need to be tested, and the with the fact, that I use dbunit to mock my database, am I allowed to use this setup for unit tests of my service layer?
我不会将 DBunit 的使用称为数据库模拟。它肯定有助于填充数据库,但仍然需要数据库来运行测试,并且您的域层将被执行(JPA、Hibernate 或任何 ORM 框架将生成将针对数据库执行的 SQL)。如果你真的想模拟域层和数据库,那么你应该考虑使用模拟(许多模拟库可以帮助实现这一点)。
至于最后一个问题,如果此设置适用于您的项目,我想它没问题,但我不会将其称为单元测试,而是集成测试。您必须接受,如果您的域层由于某种原因发生更改,它可能会破坏您的服务层测试。
这两种方法(单元与集成)各有利弊。如果它可以帮助您以高质量和良好的可维护性发展项目,那么就没有“正确”或“错误”的方法。
关于java - 服务层测试 : Is it still unit testing when using dbUnit and not mocking a native Spring domain layer?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46155130/