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. I want to invoke the real method of the JPA repository and I want to get the real db result instead of mocking it. 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
.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.