简体   繁体   中英

Spring Boot DBUnit test getting NoSuchBeanDefinitionException

I am trying to create a simple SpringBoot DB Unit repository test but I'm getting a:

NoSuchBeanDefinitionException: No qualifying bean of type 'example.ItemRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

My Gradle Dependencies

compile('org.springframework.boot:spring-boot-starter-data-jpa')
runtime('com.h2database:h2')

testCompile("junit:junit")
testCompile("org.assertj:assertj-core:3.8.0")
testCompile('org.springframework.boot:spring-boot-starter-test')

testCompile("org.dbunit:dbunit:2.4.9")
testCompile("com.github.springtestdbunit:spring-test-dbunit:1.0.0")

My Repository in item-repository/src/main/java/example/ItemRepository

@Component
public interface ItemRepository extends CrudRepository<Item, Long> {
}

My Repository Test in item-repository/src/test/java/example/ItemRepositoryTest

@TestExecutionListeners({DependencyInjectionTestExecutionListener.class, DirtiesContextTestExecutionListener.class,
        TransactionalTestExecutionListener.class, DbUnitTestExecutionListener.class})
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = RepositoryTestConfiguration.class)
@DirtiesContext
public class ItemRepositoryTest {

    @Autowired
    private ItemRepository repository;

    @Test
    @DatabaseSetup("Empty.xml")
    public void save() {
        // Given
        Item item = new Item

        // When
        Item response = repository.save(item);

        // Then
        assertThat(response.getId()).isNotNull();
    }

}

My Test Configuration in item-repository/src/main/test/example/configuration/RepositoryTestConfiguration

@Configuration
public class RepositoryTestConfiguration {
}

What do I need to include in my RepositoryTestConfiguration to get this to work?

Note: I keep my repositories in a seperate module to my Application class so I can't refer to that class in the test configuration

You have to enable jpa repository like following annotation:

@EnableJpaRepositories(basePackages = {"com.hop.repository"})

on your RepositoryTestConfiguration class then your repositories beans can be autowired.

Oh ok as you are using spring boot, it enables auto configurations. So just use @SpringApplicationConfiguration instead of @ContextConfiguration.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM