Home > Blockchain >  How do I use mockito to test JPA methods?
How do I use mockito to test JPA methods?

Time:07-26

I recently learned and have been using Mockito for the past two months but faced a roadblock. I have created a query that filters for various complex conditions and I would like to test the behavior and functionality based on given inputs.

With Mockito, we can mock and define the return value but I just want to allow the filter to do its work. The problem I have is how exactly should I go about this? Is there some way to mock a database and its rows so I can allow my filter to take course and validate my filter's functionality?

Any guidance or advice would be greatly appreciated!

Thank you :)

CodePudding user response:

As commented by @Willem, it's strongly recommended to have more realistic test, even not against some In-Memory DB like H2, but real Docker/Sql-engine (like for MySql: ch.vorburger.mariadb4j.DB.newEmbeddedDB(DBConfigurationBuilder.newBuilder().build()).start())). This will ensure the real SQLs will be tested. There are some differences between real DB engine and the In-Memory, that you'd like to discover before deploying.

Anyway, if you'd like to have it mocked, you can do:

// in the @Before
SomeJpaRepository someRepo = Mockito.mock(SomeJpaRepository.class);
ReflectionTestUtils.setField(someService, "someJpsRepo", someRepo);

// in the @Test 
Mockito.when(someRepo.saveAll(ArgumentMatchers.any())).thenReturn(new ArrayList<>());
Mockito.when(someRepo.getRecordsByFilter(request, PageRequest.of(0, 100))).thenReturn(getMockAnswer());

Now, when I'm reading again your question: "I have created a query that filters..." I think you cannot do it with a mock, as you'd like to test the SQL itself. To achieve this you can insert the test rows from a CSV.

  • Related