mardi 8 septembre 2020

Cannot determine dialect when Mocking JdbcTemplate bean

I'm working on a Spring Boot application using the Kotlin language. I have recently tried to update the version of Spring Boot from 2.2.4.RELEASE to 2.3.3.RELEASE.

This update ships some breaking changes. This is the one I am dealing with: https://docs.spring.io/spring-data/jdbc/docs/current/reference/html/#jdbc.dialects .

One of my tests is mocking the jdbcTemplate Bean:

class MyTestClass {

    @MockBean
    lateinit var jdbcTemplate: JdbcTemplate

    @Test
    fun aTest() {
        // do something with jdbcTemplate
    }

}

Once I update Spring boot to the new version, and try to run this test the ApplicationContext fails to load, because one of my Repository Beans (which is not involved by this test class) cannot be created. The stacktrace reveals the following:

...
Caused by: org.springframework.data.jdbc.repository.config.DialectResolver$NoDialectException: Cannot determine a dialect for jdbcTemplate bean. Please provide a Dialect.
    at org.springframework.data.jdbc.repository.config.DialectResolver.lambda$getDialect$2(DialectResolver.java:80)
    at java.util.Optional.orElseThrow(Optional.java:290)
    at org.springframework.data.jdbc.repository.config.DialectResolver.getDialect(DialectResolver.java:79)
    at org.springframework.data.jdbc.repository.config.AbstractJdbcConfiguration.jdbcDialect(AbstractJdbcConfiguration.java:144)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154)
    ... 135 more

In other words, the DialectResolver fails to detect the dialect for the JdbcTemplate bean, which my org.springframework.data.Repository implementations depend on (and to my understanding this happens because the mocked JdbcTemplate is bound to a null DataSource).

My repositories look like this:

@org.springframework.stereotype.Repository
interface MyRepository : Repository<MyEntityModel, Long> {
    @Query(
        value = """select * from mytable"""
    )
    fun someMethod(): List<MyEntityModel>
}

My question is: How I can avoid this kind of error and still be able to mock the response of the jdbctemplate? Could there be something wrong with my project structure? It seems odd that using @MockBean on a test class should break it because a Repository that is not related to the test is affected.

Aucun commentaire:

Enregistrer un commentaire