Jakob Benz
Jakob Benz

Reputation: 127

No qualifying bean for autowired JPA repository in JUnit test in Spring Boot application

I have several repositories extending JpaRepository. Now I want to test the custom queries I added in a unit test using a real instance of an H2 database (not in-memory - so that I can inspect the database using the web console).

However, auto-wiring the repository in the unit does not work, I always get a NoSuchBeanDefinitionException: No qualifying bean of type ... UserRepository available.

The code of the repository and the unit test is listed below. Thanks for any help!

UserRepository

public interface UserRepository extends JpaRepository<User, Long> {}


UserRepositoryTests

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
@ContextConfiguration(classes = TestConfiguration.class)
@Transactional
public class UserRepositoryTests {

    @Autowired
    private UserRepository userRepository;

    @Test
    @Commit
    public void test() throws AESEncryptionException {
        User user = new User().setFirstName("ABC").setLastName("XYZ");
        user = userRepository.save(user);
        assertNotNull(user.getId());
    }

}


TestConfiguration

@Configuration
@EnableAutoConfiguration
@ComponentScan
@PropertySource("classpath:/application.properties")
public class TestConfiguration {}


application.properties

spring.datasource.url = jdbc:h2:file:./db/app-data
spring.datasource.driverClassName = org.h2.Driver
spring.jpa.database-platform = org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto = update
spring.h2.console.settings.web-allow-others = true

EDIT: As suggested by Mensur Qulami, removing @ContextConfiguration(classes = TestConfiguration.class) did the trick, since this is already covered by @SpringBootTest.

Upvotes: 0

Views: 4259

Answers (1)

Dirk Deyne
Dirk Deyne

Reputation: 6936

You could use DataJpaTest in combination with @AutoConfigureTestDatabase(replace=Replace.NONE) to use your 'real' database

@RunWith(SpringRunner.class)
@DataJpaTest (showSql = true )
@AutoConfigureTestDatabase(replace=Replace.NONE)
public class UserRepositoryTests {

    @Autowired
    private UserRepository userRepository;

    ....

Upvotes: 2

Related Questions