-1

I do some Test Configuration. I am surprised all is OK in first scenario but not in second.

In scr/main/java, I got this Controller

@RestController
@RequestMapping("/v1")
public class PostgressControllerSpringData {

    @Resource
    PersonneRepository personneRepository;

    @GetMapping("/persist")
    public ResponseEntity<String> persistOne() {
        Personne p = new Personne();
        personneRepository.save(p);
        return new ResponseEntity<String>("persistence ok", HttpStatus.ACCEPTED);
    }

In scr/main/test, I got this configuration class

@TestConfiguration
public class ServiceConfiguration {

    @Bean
    public PostgressControllerSpringData getBean() {
        return new PostgressControllerSpringData();
    }

Now, in a test class, when I do

@RunWith(SpringRunner.class)
@DataJpaTest
@AutoConfigureTestDatabase(replace = Replace.NONE)
public class SCRIntegrationTest {

    @Autowired
    private PostgressControllerSpringData myController;

    @Autowired
    PersonneRepository dao;

    @Test
    public void m() {

        myController.persistOne();
        assertEquals(1, dao.findAll().size());
        // here, my test is successful

==> All is fine.

But if I do that.

@RunWith(SpringRunner.class)
@DataJpaTest
@AutoConfigureTestDatabase(replace = Replace.NONE)
public class SCRIntegrationTest {

    @Autowired
    private PostgressControllerSpringData myController;

    @Autowired
    PersonneRepository dao;

    @Test
    public void m() {

        WebTestClient testClient =     WebTestClient.bindToController(myController).build();

==> The code stops with the message

Injection of resource dependencies failed; No qualifying bean of type PersonneRepository' available:

I am surprised because in my first scenario, field PersonneRepository of instance PostgressControllerSpringData is well injected. But in second, Spring tells to me that injection fails!

Nkosi
  • 235,767
  • 35
  • 427
  • 472
electrode
  • 205
  • 1
  • 4
  • 16

1 Answers1

0

DataJpaTest is not intended to load controller and in general Web layer. Only database related beans (like DAOs) will be loaded. This is also written in documentation

Can be used when a test focuses only (highlighted with bold :) ) on JPA components.

If you want to load also a web layer (and as a result being able to inject controllers into the test) consider using @SpringBootTest annotation instead

Mark Bramnik
  • 39,963
  • 4
  • 57
  • 97