【发布时间】:2021-11-30 18:52:40
【问题描述】:
我有以下存储库接口,该接口正在我的服务类中使用。
@Repository
public interface InventoryRepository extends JpaRepository<Inventory, Integer> {
Inventory findByInventoryIdAndCompanyId(Integer inventoryId, Integer companyId);
}
在我的服务测试类中,我有这两个依赖项
@InjectMocks
InventoryService inventoryService;
@Mock
InventoryRepository inventoryRepository;
另外,下面是我在同一个类中的测试方法
@Test
public void getInventoryByIdTest() {
when(inventoryRepository.findByInventoryIdAndCompanyId(16591,1)).thenCallRealMethod();
Assertions.assertEquals(16591,inventoryService.getInventoryById(16591 , 1).getInventoryId());
}
我正在尝试为服务编写测试用例,该服务在内部调用 JPA 存储库方法以从 DB 获取数据。我想调用 JPA 存储库的真实方法,并且我想获得真实的数据库结果而不是模拟它。但它不起作用并引发以下错误。
org.mockito.exceptions.base.MockitoException:
Cannot call abstract real method on java object!
Calling real methods is only possible when mocking non abstract method.
//correct example:
when(mockOfConcreteClass.nonAbstractMethod()).thenCallRealMethod();
有什么办法可以解决吗?
【问题讨论】:
-
既然你提到它是一个springboot服务,你需要确保首先加载spring上下文。您拥有的模拟不会加载弹簧上下文。示例 - baeldung.com/…
标签: spring-boot spring-data-jpa mockito junit5 powermockito