mardi 21 avril 2020

How to autowire repository in DataJpaTest?

I tried to autowire my CrudRepository within a DataJpaTest

public class MyJPATest {

@Autowired
MyRepo myRepo;


@Test
public void doSomething() {
    keywordRepo.save(new MyEntity("John","Doe"));
}

MyRepo:

@Repository
public interface MyRepo extends CrudRepository<MyEntity, Long>{

}

After getting a NullPointerException, I found sme solutions (https://stackoverflow.com/questions/48347088) that should help there and I tried the following

@DataJpaTest(includeFilters = @ComponentScan.Filter(type = FilterType.ANNOTATION, classes = Repository.class))

public class MyJPATest {

@Autowired
MyRepo myRepo;


@Test
public void doSomething() {
    keywordRepo.save(new MyEntity("John","Doe"));
}

And

@DataJpaTest
@Import(MyRepo.class)
public class MyJPATest {

@Autowired
MyRepo myRepo;


@Test
public void doSomething() {
    keywordRepo.save(new MyEntity("John","Doe"));
}

Both approaches and many other things I have tried do not change the result. No matter what I do, the repo stays null.

Aucun commentaire:

Enregistrer un commentaire