嗨,我是新的Mockito框架,正在尝试为我的spring-boot应用程序编写一些单元测试。我模拟了我的服务,所以每次Mockito运行时,它都在使用一些空的模拟数据库,我想使用一些准备好的嵌入式数据库,让我给你解释一下用例。我有一个实体,比方说EntityX。
@Entity
@Table(name = "ENTITYX")
public class EntityX{
private long id;
// Some other properties
}我创建了它的存储库,我有一个定义方法process的服务,这个方法接受entityId的参数,并按如下方式从DB中获取该实体。
@Service
public class MyService{
@Autowired
EntityXRepository repository;
public Object process(long entityId){
EntityX entity = repository.findById(entityId).orElseThrow(()-> new RuntimeException("No Entity found with id "+entityId));
// Does some operation with entity object.
...
return someObject;
}
}现在在我的单元测试中,我使用@Mock模拟我的服务,并调用process (某个is );但是process方法总是抛出异常,因为在mock db中不存在someid的实体。插入到EntityX表超出了我的应用程序的范围,所以有没有可能提供一些数据库文件(一些嵌入式DB文件)给Mockito,以便它可以从提供的数据库记录开始,而不是空的db?
发布于 2021-11-09 15:57:44
如果您真的想在单元测试中使用数据库,那么您可以为这个用例创建一个application-test.properties文件并使用h2数据库。
<!-- https://mvnrepository.com/artifact/com.h2database/h2 -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.200</version>
<scope>test</scope>
</dependency>为了在您的单元测试中加载测试概要文件,您可以在您的测试类之上使用此注释。
@ActiveProfiles("test")为了插入脚本,您可以在下面的链接中获得更多信息,这将解决在单元测试开始时加载数据库的问题。
H2 in-memory database initialization with data
另外,出于好奇,如果您想避免数据库交互,您可以模拟EntityXRepository repository;,并使用模拟来模拟所需的行为。
@SpringBootTest
@ActiveProfiles("test")
class TestService{
@MockBean
EntityXRepository repository;
@Test
void test_somescenario_success(){
Mockito.when(repository.findById("someId")).thenReturn(someEntityX);
//other mocks, service call and assertions
}
}https://stackoverflow.com/questions/69851848
复制相似问题