How to properly inject & mock a repository class' AgroalDataSource dependency? #31404
-
I've created a Quarkus 2.16.2.Final API in Kotlin & the endpoints work as expected. Now I'm trying to write my first automated tests (using Mockk), and I'm running into a problem that I believe relates to how I'm injecting a datasource into a repository class. Here's what my repository class declaration looks like:
The first hint that I might be doing something wrong is that IntelliJ displays the warning tooltip above my
I have the following code in my
Finally, I have the following VM options added to my Quarkus run/debug configuration, to ensure the
However, when I run my first API endpoint test, I get the following exception:
Seems like I'm doing something wrong somewhere... any idea what it might be? I'm gonna try and get a reproducer project going, so that it's easier to point at functional code. But I figured I'd try and explain the problem first, in case it was easy for more experienced eyes to notice what I'm doing wrong. As always, thanks in advance! |
Beta Was this translation helpful? Give feedback.
Replies: 5 comments 13 replies
-
/cc @Sanne (agroal), @barreiro (agroal), @evanchooly (kotlin), @geoand (kotlin), @yrodiere (agroal) |
Beta Was this translation helpful? Give feedback.
-
If it's of any help, here's what my test code looks like:
|
Beta Was this translation helpful? Give feedback.
-
Looking at the javadoc of
So, do something like this in order to mock the "missing" bean?
EDIT: That may not be valid Kotlin code, but you get the idea. |
Beta Was this translation helpful? Give feedback.
-
I just tried using FWIW my code is already using Regarding CDI MockLocalstorageDatasource.kt
Now I'm getting a different exception:
|
Beta Was this translation helpful? Give feedback.
-
Hi, I worked with @jehrenzweig-leagueapps to find a solution to this problem. AgroalDatasource cannot be mocked. If you need to mock low level objects, like: Connection, PreparedStatement, and ResultSet, you need to mock the Datasource. So, create an ApplicationScoped bean that receives the AgroalDatasource in constructor, and have a method that returns the datasoure cast as java.sql.Datasource (not AgroalDatasource).
This way you can mock persistence on your tests. When you run "quarkus test" you'll be using your mocks. When you run "quarkus dev" you'll be using your dev database config. |
Beta Was this translation helpful? Give feedback.
I just tried using
@BeforeAll
; still doesn't work. Nor does moving theQuarkusMock.installMockForType()
call to the test itself and foregoing use of@BeforeAll
&@BeforeEach
.FWIW my code is already using
@InjectMock
; it isn't working the way I'd expect.Regarding CDI
@Alternative
: I just tried creating the following class in/src/test/kotlin
, which uses theio.quarkus.test.Mock
annotation recommended by the documentation:MockLocalstorageDatasource.kt