spring-bootkotlinjpatesting

Error when I running test In Kotlin+Springboot


I'm currently learning Kotlin and decided to do some tests to see if my progress works so far, but I'm encountering an error when running my test. None of the solutions I've found on the internet have addressed my specific issue with any success.

I created the project with spring initializer, using IntelliJ IDEA.

The data class:

package com.refactorizando.RealState.model

import jakarta.persistence.Column
import jakarta.persistence.Entity
import jakarta.persistence.GeneratedValue
import jakarta.persistence.GenerationType
import jakarta.persistence.Id

@Entity
 data class House(
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "houseId")
    val houseId : Long?=null,
    @Column(name = "height")
    val height : Long,
    @Column(name = "length")
    val length : Long,
    @Column(name = "neighbourhood")
    val neighbourhood : String,
    @Column(name = "price")
    val price : Long

    )
package com.refactorizando.RealState.repository

import com.refactorizando.RealState.model.House
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.stereotype.Repository


@Repository
interface HouseRepository : JpaRepository<House,Long> {
}

The test:

package com.refactorizando.RealState.repository

import com.refactorizando.RealState.model.House
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertNotNull
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest


@DataJpaTest
class HouseRepositoryTest{

    @Autowired
    lateinit var houseRepository: HouseRepository
    lateinit var house : House
    @BeforeEach
    fun init(){
         house  = House(height = 1, length = 1,  neighbourhood = "Somewhere", price = 10000)
    }
    @Test
    fun shouldSave(){
        val savedHouse = houseRepository.save(house)
        assertNotNull(savedHouse)
    }

}

And I keep getting the same error below:

Failed to load ApplicationContext for [MergedContextConfiguration@777d191f testClass = com.refactorizando.RealState.repository.HouseRepositoryTest, locations = [], classes = [com.refactorizando.RealState.RealStateApplication], contextInitializerClasses = [], activeProfiles = [], propertySourceDescriptors = [], propertySourceProperties = ["org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTestContextBootstrapper=true"], contextCustomizers = [org.springframework.boot.test.autoconfigure.OnFailureConditionReportContextCustomizerFactory$OnFailureConditionReportContextCustomizer@c260bdc, org.springframework.boot.test.autoconfigure.OverrideAutoConfigurationContextCustomizerFactory$DisableAutoConfigurationContextCustomizer@3f363cf5, org.springframework.boot.test.autoconfigure.actuate.observability.ObservabilityContextCustomizerFactory$DisableObservabilityContextCustomizer@1f, org.springframework.boot.test.autoconfigure.filter.TypeExcludeFiltersContextCustomizer@34be3d80, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@cc5747f7, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizer@7b64240d, [ImportsContextCustomizer@7fc420b8 key = [org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration, org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration, org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManagerAutoConfiguration, org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration, org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration, org.springframework.boot.autoconfigure.sql.init.SqlInitializationAutoConfiguration, org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration, org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration, org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.JdbcClientAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration]], org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@5049d8b2, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@2a3591c5, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.web.reactor.netty.DisableReactorResourceFactoryGlobalResourcesContextCustomizerFactory$DisableReactorResourceFactoryGlobalResourcesContextCustomizerCustomizer@76ba13c, org.springframework.test.context.support.DynamicPropertiesContextCustomizer@0, org.springframework.boot.test.context.SpringBootTestAnnotation@d6b877fa], contextLoader = org.springframework.boot.test.context.SpringBootContextLoader, parent = null]
java.lang.IllegalStateException: Failed to load ApplicationContext for [MergedContextConfiguration@777d191f testClass = com.refactorizando.RealState.repository.HouseRepositoryTest, locations = [], classes = [com.refactorizando.RealState.RealStateApplication], contextInitializerClasses = [], activeProfiles = [], propertySourceDescriptors = [], propertySourceProperties = ["org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTestContextBootstrapper=true"], contextCustomizers = [org.springframework.boot.test.autoconfigure.OnFailureConditionReportContextCustomizerFactory$OnFailureConditionReportContextCustomizer@c260bdc, org.springframework.boot.test.autoconfigure.OverrideAutoConfigurationContextCustomizerFactory$DisableAutoConfigurationContextCustomizer@3f363cf5, org.springframework.boot.test.autoconfigure.actuate.observability.ObservabilityContextCustomizerFactory$DisableObservabilityContextCustomizer@1f, org.springframework.boot.test.autoconfigure.filter.TypeExcludeFiltersContextCustomizer@34be3d80, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@cc5747f7, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizer@7b64240d, [ImportsContextCustomizer@7fc420b8 key = [org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration, org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration, org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManagerAutoConfiguration, org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration, org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration, org.springframework.boot.autoconfigure.sql.init.SqlInitializationAutoConfiguration, org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration, org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration, org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.JdbcClientAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration]], org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@5049d8b2, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@2a3591c5, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.web.reactor.netty.DisableReactorResourceFactoryGlobalResourcesContextCustomizerFactory$DisableReactorResourceFactoryGlobalResourcesContextCustomizerCustomizer@76ba13c, org.springframework.test.context.support.DynamicPropertiesContextCustomizer@0, org.springframework.boot.test.context.SpringBootTestAnnotation@d6b877fa], contextLoader = org.springframework.boot.test.context.SpringBootContextLoader, parent = null]
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:180)
    at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:130)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:155)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:111)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:260)
    at org.springframework.test.context.junit.jupiter.SpringExtension.postProcessTestInstance(SpringExtension.java:160)
    at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:184)
    at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:215)
    at java.base/java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:197)
    at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:215)
    at java.base/java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1709)
    at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:570)
    at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:560)
    at java.base/java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:151)
    at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:174)
    at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:265)
    at java.base/java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:636)
    at java.base/java.util.Optional.orElseGet(Optional.java:364)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1597)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1597)
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'testEntityManager' defined in class path resource [org/springframework/boot/test/autoconfigure/orm/jpa/TestEntityManagerAutoConfiguration.class]: Unsatisfied dependency expressed through method 'testEntityManager' parameter 0: No qualifying bean of type 'jakarta.persistence.EntityManagerFactory' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
at org.springframework.beans.factory.support.ConstructorResolver
    .createArgumentArray(ConstructorResolver.java : 804) at org.springframework
    .beans.factory.support.ConstructorResolver
    .instantiateUsingFactoryMethod(ConstructorResolver.java : 546) at org
    .springframework.beans.factory.support.AbstractAutowireCapableBeanFactory
    .instantiateUsingFactoryMethod(
        AbstractAutowireCapableBeanFactory.java : 1361) at org.springframework
    .beans.factory.support.AbstractAutowireCapableBeanFactory
    .createBeanInstance(AbstractAutowireCapableBeanFactory.java : 1191) at org
    .springframework.beans.factory.support.AbstractAutowireCapableBeanFactory
    .doCreateBean(AbstractAutowireCapableBeanFactory.java : 563) at org
    .springframework.beans.factory.support.AbstractAutowireCapableBeanFactory
    .createBean(AbstractAutowireCapableBeanFactory.java : 523) at org
    .springframework.beans.factory.support.AbstractBeanFactory
    .lambda$doGetBean$0(AbstractBeanFactory.java : 339) at org.springframework
    .beans.factory.support.DefaultSingletonBeanRegistry
    .getSingleton(DefaultSingletonBeanRegistry.java : 347) at org
    .springframework.beans.factory.support.AbstractBeanFactory
    .doGetBean(
        AbstractBeanFactory.java : 337) at org.springframework.beans.factory
    .support.AbstractBeanFactory.getBean(AbstractBeanFactory.java : 202) at org
    .springframework.beans.factory.support.DefaultListableBeanFactory
    .instantiateSingleton(DefaultListableBeanFactory.java : 1155) at org
    .springframework.beans.factory.support.DefaultListableBeanFactory
    .preInstantiateSingleton(DefaultListableBeanFactory.java : 1121) at org
    .springframework.beans.factory.support.DefaultListableBeanFactory
    .preInstantiateSingletons(DefaultListableBeanFactory.java : 1056) at org
    .springframework.context.support.AbstractApplicationContext
    .finishBeanFactoryInitialization(AbstractApplicationContext.java : 987)
        at org.springframework.context.support.AbstractApplicationContext
    .refresh(AbstractApplicationContext.java : 627) at org.springframework.boot
    .SpringApplication.refresh(SpringApplication.java : 752) at org
    .springframework.boot.SpringApplication
    .refreshContext(SpringApplication.java : 439) at org.springframework.boot
    .SpringApplication.run(SpringApplication.java : 318) at org.springframework
    .boot.test.context.SpringBootContextLoader
    .lambda$loadContext$3(SpringBootContextLoader.java : 144) at org
    .springframework.util.function.ThrowingSupplier
    .get(ThrowingSupplier.java : 58) at org.springframework.util.function
    .ThrowingSupplier.get(ThrowingSupplier.java : 46) at org.springframework
    .boot.SpringApplication.withHook(SpringApplication.java : 1461) at org
    .springframework.boot.test.context.SpringBootContextLoader$ContextLoaderHook
    .run(SpringBootContextLoader.java : 563) at org.springframework.boot.test
    .context.SpringBootContextLoader
    .loadContext(SpringBootContextLoader.java : 144) at org.springframework.boot
    .test.context.SpringBootContextLoader
    .loadContext(SpringBootContextLoader.java : 110) at org.springframework.test
    .context.cache.DefaultCacheAwareContextLoaderDelegate
    .loadContextInternal(
        DefaultCacheAwareContextLoaderDelegate.java : 225) at org
    .springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate
    .loadContext(
        DefaultCacheAwareContextLoaderDelegate.java : 152)... 19 more Caused by
    : org.springframework.beans.factory
    .NoSuchBeanDefinitionException
    : No qualifying bean of type
      'jakarta.persistence.EntityManagerFactory' available
    : expected at least
      1 bean which qualifies as autowire candidate.Dependency annotations : {}
at org.springframework.beans.factory.support.DefaultListableBeanFactory
    .raiseNoMatchingBeanFound(DefaultListableBeanFactory.java : 2207) at org
    .springframework.beans.factory.support.DefaultListableBeanFactory
    .doResolveDependency(DefaultListableBeanFactory.java : 1630) at org
    .springframework.beans.factory.support.DefaultListableBeanFactory
    .resolveDependency(DefaultListableBeanFactory.java : 1555) at org
    .springframework.beans.factory.support.ConstructorResolver
    .resolveAutowiredArgument(ConstructorResolver.java : 913) at org
    .springframework.beans.factory.support.ConstructorResolver
    .createArgumentArray(ConstructorResolver.java : 791)... 45 more

    Error creating bean with name 'testEntityManager' defined in
    class path resource[org / springframework / boot / test / autoconfigure /
                        orm / jpa / TestEntityManagerAutoConfiguration.class]
    : Unsatisfied dependency expressed through method
      'testEntityManager' parameter 0
    : No qualifying bean of type
      'jakarta.persistence.EntityManagerFactory' available
    : expected at least
      1 bean which qualifies as autowire candidate.Dependency annotations : {}
org.springframework.beans.factory
    .UnsatisfiedDependencyException
    : Error creating bean with name 'testEntityManager' defined in class path
          resource[org / springframework / boot / test / autoconfigure / orm /
                   jpa / TestEntityManagerAutoConfiguration.class]
    : Unsatisfied dependency expressed through
          method 'testEntityManager' parameter 0
    : No qualifying bean of
          type 'jakarta.persistence.EntityManagerFactory' available
    : expected at least 1 bean which qualifies
          as autowire candidate.Dependency annotations : {}
at app  // org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:804)
        at app  // org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:546)
            at app  // org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1361)
                at app  // org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1191)
                    at app  // org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:563)
                        at app  // org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:523)
                            at app  // org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:339)
                                at app  // org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:347)
                                    at app  // org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:337)
                                        at app  // org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
                                            at app  // org.springframework.beans.factory.support.DefaultListableBeanFactory.instantiateSingleton(DefaultListableBeanFactory.java:1155)
                                                at app  // org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingleton(DefaultListableBeanFactory.java:1121)
                                                    at app  // org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:1056)
                                                        at app  // org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:987)
                                                            at app  // org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:627)
                                                                at app  // org.springframework.boot.SpringApplication.refresh(SpringApplication.java:752)
                                                                    at app  // org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:439)
                                                                        at
                                                                            app  // org.springframework.boot.SpringApplication.run(SpringApplication.java:318)
                                                                                at
                                                                                    app  // org.springframework.boot.test.context.SpringBootContextLoader.lambda$loadContext$3(SpringBootContextLoader.java:144)
                                                                                        at
                                                                                            app  // org.springframework.util.function.ThrowingSupplier.get(ThrowingSupplier.java:58)
                                                                                                at
                                                                                                    app  // org.springframework.util.function.ThrowingSupplier.get(ThrowingSupplier.java:46)
                                                                                                        at
                                                                                                            app  // org.springframework.boot.SpringApplication.withHook(SpringApplication.java:1461)
                                                                                                                at
                                                                                                                    app  // org.springframework.boot.test.context.SpringBootContextLoader$ContextLoaderHook.run(SpringBootContextLoader.java:563)
                                                                                                                        at
                                                                                                                            app  // org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:144)
                                                                                                                                at
                                                                                                                                    app  // org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:110)
                                                                                                                                        at
                                                                                                                                            app  // org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:225)
                                                                                                                                                at
                                                                                                                                                    app  // org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:152)
                                                                                                                                                        at
                                                                                                                                                            app  // org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:130)
                                                                                                                                                                at app  // org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:155)
                                                                                                                                                                    at app  // org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:111)
                                                                                                                                                                        at app  // org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:260)
                                                                                                                                                                            at app  // org.springframework.test.context.junit.jupiter.SpringExtension.postProcessTestInstance(SpringExtension.java:160)
                                                                                                                                                                                at java
                                                                                                                                                                                    .base
    @23.0.2 /
    java.util.stream.ForEachOps$ForEachOp$OfRef
        .accept(ForEachOps.java : 184) at java.base @23.0.2 /
    java.util.stream.ReferencePipeline$3$1
        .accept(ReferencePipeline.java : 215) at java.base @23.0.2 /
    java.util.stream.ReferencePipeline$2$1
        .accept(ReferencePipeline.java : 197) at java.base @23.0.2 /
    java.util.stream.ReferencePipeline$3$1
        .accept(ReferencePipeline.java : 215) at java.base @23.0.2 /
    java.util.ArrayList$ArrayListSpliterator
        .forEachRemaining(ArrayList.java : 1709) at java.base @23.0.2 /
    java.util.stream.AbstractPipeline
        .copyInto(AbstractPipeline.java : 570) at java.base @23.0.2 /
    java.util.stream.AbstractPipeline
        .wrapAndCopyInto(AbstractPipeline.java : 560) at java.base @23.0.2 /
    java.util.stream.ForEachOps$ForEachOp
        .evaluateSequential(ForEachOps.java : 151) at java.base @23.0.2 /
    java.util.stream.ForEachOps$ForEachOp$OfRef
        .evaluateSequential(ForEachOps.java : 174) at java.base @23.0.2 /
    java.util.stream.AbstractPipeline
        .evaluate(AbstractPipeline.java : 265) at java.base @23.0.2 /
    java.util.stream.ReferencePipeline
        .forEach(ReferencePipeline.java : 636) at java.base @23.0.2 /
    java.util.Optional.orElseGet(Optional.java : 364) at java.base @23.0.2 /
    java.util.ArrayList.forEach(ArrayList.java : 1597) at java.base @23.0.2 /
    java.util.ArrayList.forEach(ArrayList.java : 1597) Caused by
    : org.springframework.beans.factory
          .NoSuchBeanDefinitionException
    : No qualifying bean of type
      'jakarta.persistence.EntityManagerFactory' available
    : expected at least
      1 bean which qualifies as autowire candidate.Dependency annotations : {}
at app  // org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:2207)
    at app  // org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1630)
        at app  // org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1555)
            at app  // org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:913)
                at app  // org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:791)
    ... 45 more

Here is the repository of the code.

I know I'm not providing a ton of info, but the truth is I do not know what else to say, I've tried different solutions posted online and no one seem to fit this problem.


Solution

  • The exception is thrown because you do not have EntityManagerFactory bean in your spring container.

    In order to avoid manually creating it, you could add the following dependency:

    implementation("org.springframework.boot:spring-boot-starter-data-jpa")
    

    spring-boot-starter-data-jpa creates beans based on your application.yaml that are needed to work with persistence