繁体   English   中英

springboot服务如何在Junit5 mockito测试用例中调用jpa仓库的真实方法

[英]How to call real methods of jpa repository in Junit5 mockito test cases for springboot services

我有下面的存储库接口,它正在我的服务类中使用。

@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 存储库的真实方法,我想获得真实的 db 结果而不是模拟它。 但它不起作用并抛出以下错误。

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();

有没有可能的方法来解决它?

让我们尝试将接口InventoryService替换为其在您的 junit 中的实现,并使用@Spy而不是@Mock

暗示

您的测试是集成测试,而不是单元测试。 您正在测试您的应用程序是否与您的数据库通信没有任何问题; 不幸的是,这种类型的测试需要很多资源和太多时间(让我们想象一下测试的手,每个都打开一个到数据库的连接)。 单元测试对于验证您的应用程序的业务逻辑非常有用,并且由于它们不需要大量资源,如果需要,我们可以使用模拟接口或服务或其他任何东西,每次测试应该花费不到一秒钟的时间.

我建议你阅读 这篇Martin Flower 的文章

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM