Open yrodiere opened 6 months ago
Oddly enough, I could not reproduce this problem in either hibernate-orm-quickstart
or hibernate-orm-panache-quickstart
.
For the former the test I added was:
@QuarkusTest
public class MockTest {
@InjectMock
EntityManager em;
@Test
public void test() {
Fruit mockResponse = new Fruit();
mockResponse.setId(1);
mockResponse.setName("mock");
Mockito.when(em.find(Fruit.class, 1)).thenReturn(mockResponse);
Fruit fruit = em.find(Fruit.class, 1);
Assertions.assertEquals("mock", fruit.getName());
}
}
For the latter it was essentially the same thing but using FruitEntity
instead of Fruit
.
@geoand I think that in order to reproduce this, you need to mock a method whose return type is overloaded in Session
. Like createNativeQuery
.
Oh, you are right, adding:
Query mock = Mockito.mock(Query.class);
Mockito.when(em.createNativeQuery("SELECT 1 FROM FRUIT")).thenReturn(mock);
surfaces the problem.
Honestly, I don't think we can do much...
Yeah I don't know if we can solve this either, but we might be able to forbid @InjectMock EntityManager
and provide a clear exception + document the limitation, at least.
Or more generally forbid @InjectMock A
where we know that matching CDI beans are exposed with type B extends A
(so @InjectMock
should use type B
).
That's probably a good idea
Description
While
@InjectMock Session
works fine to mock the Hibernate ORM session, oddly@InjectMock EntityManager
doesn't, even if a given test only usesEntityManager
(e.g. using Panache): any method you'll mock will fail because something expect you to use theSession
return type, even though you're mocking aEntityManager
object (see stracktrace near the bottom).This is a bit counter-intuitive, so we should probably look into either making
@InjectMock EntityManager
work correctly, or documenting the limitation and adding clear exception messages when someone tries to do@InjectMock EntityManager
("@InjectMock
doesn't work withEntityManager
, useSession
instead").Stacktrace from: https://github.com/quarkusio/quarkus/issues/40475#issuecomment-2117803810
Implementation ideas
No response