简体   繁体   中英

Spring Boot Service using Jpa repository Testing

I want to test a Spring @Service.

This service has method using a JpaRepository autowired.

That is the code of the simple service.

@Service
public class PersonneService {

    @Autowired
    PersonneRepository personneRepository;

    public Personne createPersonne(Personne personne) {
        return personneRepository.save(personne);
    }

I am trying to test it but i have an error

Unsatisfed dependency expressed for the service.
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.symit.gmah.emprunt.services.PersonneHandleService': Unsatisfied dependency expressed through field 'personneService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.symit.gmah.emprunt.services.PersonneService' available: expected at least 1 bean which qualifies as autowire candidate. .....

That is the code of my test.

@RunWith(SpringRunner.class)
@DataJpaTest
public class PersonneHandleService {

    @Autowired
    PersonneService personneService;

    @Test
    public void PersonneServiceCreateTest() {
        Personne personne = new Personne("John","Doe","43343");

        personne = personneService.createPersonne(personne);
        assertNotNull(personne.getId());

    }

Can you help me and explain me what I have to do.

Thanks

PS: I am using embeded H2 Database;

That is my configuration:
# Enabling H2 Console
spring.h2.console.enabled=true
jdbc.driverClassName=org.h2.Driver
#jdbc.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
jdbc.url=jdbc:h2:~/gmahdb;DB_CLOSE_DELAY=-1
jdbc.username=sa
jdbc.password=sa

You still have to add your services to the Spring context. You now only setup your JPA (entities and repositories).

As an alternative, you could also just use @SpringBootTest in stead of @DataJpaTest. This loads the entire application for testing. Depending on the size and number of dependencies of your application this might not be the optimal scenario.

From the documentation of DataJpaTest:

Annotation that can be used in combination with @RunWith(SpringRunner.class) for a typical JPA test. Can be used when a test focuses only on JPA components. Using this annotation will disable full auto-configuration and instead apply only configuration relevant to JPA tests.

and...

If you are looking to load your full application configuration, but use an embedded database, you should consider @SpringBootTest combined with @AutoConfigureTestDatabase rather than this annotation.

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