[英]How to call real methods of jpa repository in Junit5 mockito test cases for springboot services
I have below repository interface which is getting used in my service class.我有下面的存储库接口,它正在我的服务类中使用。
@Repository
public interface InventoryRepository extends JpaRepository<Inventory, Integer> {
Inventory findByInventoryIdAndCompanyId(Integer inventoryId, Integer companyId);
}
In My service test class, I have these two dependencies在我的服务测试类中,我有这两个依赖项
@InjectMocks
InventoryService inventoryService;
@Mock
InventoryRepository inventoryRepository;
Also, Below is my test method in the same class另外,下面是我在同一个类中的测试方法
@Test
public void getInventoryByIdTest() {
when(inventoryRepository.findByInventoryIdAndCompanyId(16591,1)).thenCallRealMethod();
Assertions.assertEquals(16591,inventoryService.getInventoryById(16591 , 1).getInventoryId());
}
I am trying to write a test case for a service and this service internally calls the JPA repository method to get the data from DB.我正在尝试为服务编写测试用例,该服务在内部调用 JPA 存储库方法以从 DB 获取数据。 I want to invoke the real method of the JPA repository and I want to get the real db result instead of mocking it.
我想调用 JPA 存储库的真实方法,我想获得真实的 db 结果而不是模拟它。 But it is not working and throwing the below error.
但它不起作用并抛出以下错误。
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();
Is there any possible way to work it out?有没有可能的方法来解决它?
Let's try to replace the interface InventoryService
with its implementation in your junit and use @Spy
instead of @Mock
.让我们尝试将接口
InventoryService
替换为其在您的 junit 中的实现,并使用@Spy
而不是@Mock
。
Hint暗示
Your test is an integration test, not an unit test.您的测试是集成测试,而不是单元测试。 You are testing that your application comunicates without any problems with your database;
您正在测试您的应用程序是否与您的数据库通信没有任何问题; unfortunately this type of test requires many resources and too much time (let's immagine having handreds of test and each of this open a connection to the database).
不幸的是,这种类型的测试需要很多资源和太多时间(让我们想象一下测试的手,每个都打开一个到数据库的连接)。 The unit tests are useful in order to verify the buisness logic of your application and, since they don't require a lot of resources and if they do we can use mock interfaces or services or whatever, they should take less then one second per test.
单元测试对于验证您的应用程序的业务逻辑非常有用,并且由于它们不需要大量资源,如果需要,我们可以使用模拟接口或服务或其他任何东西,每次测试应该花费不到一秒钟的时间.
I suggest you to read this of article of Martin Flower我建议你阅读 这篇Martin Flower 的文章
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.