Spring Boot 3 Unit Test cannot convert Duration value when ContextConfiguration is used to provide test scope

37 views Asked by At

TL/DR -> Does anyone know how to enable the automatic ApplicationConversionService in a Junit test that also specifies a ContextConfiguration to only spin up one ConfigurationProperties class that has a java.time.Duration property?

While testing, I only want to stand up enough Application context to be able to test my @ConfigurationProperties class.
To do so, I'm using ContextConfiguration to specify the class I want to be used.
My properties class works just fine when everything is a String, but the second I add a property that is java.time.Duration the Only unit tests start to fail.\

From the research I've done, it appears to be an issue with the ApplicationConversionService not being registered.
While using only @SpringBootTest does work, it also requires starting up the entire application context and all properties and configurations.

in a basic spring boot application from start.spring.io here are the classes I used to reproduce this
kotlin 1.8.22
spring-boot 3.2.2

application.yml

test:
  something:
    expiration: PT3H45M

Configuration Properties Class

package com.example.demo.configuration.properties

import org.springframework.boot.context.properties.ConfigurationProperties
import java.time.Duration

@ConfigurationProperties(prefix = "test.something")
data class SomethingProps(
    val expiration: Duration
)

Configuration Properties Test

package com.example.demo.configuration.properties

import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.context.properties.EnableConfigurationProperties
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.test.context.ContextConfiguration
import org.springframework.test.context.junit.jupiter.SpringExtension
import java.time.Duration

@ExtendWith(SpringExtension::class)
@EnableConfigurationProperties(value = [SomethingProps::class])
@ContextConfiguration(classes = [SomethingProps::class])
@SpringBootTest
class SomethingPropsTest(
    @Autowired private val somethingProps: SomethingProps
) {
    @Test
    fun `confirm that something properties function correctly`() {
        Assertions.assertEquals(
            Duration.parse("PT3H45M"),
            somethingProps.expiration,
        )
    }
}

Exception:

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'java.time.Duration' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
0

There are 0 answers