Search code examples
springjunit5spring-test

How to "Autowire" repository in JUnit 5 test


I don't understand yow to refer to my services/repositories in a JUnit 5 test. I'm trying to annotate it the same as I do my Main class which runs fine:

@ComponentScan
@EnableJpaRepositories
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class TestMessageRepository {
    @Autowired
    private MessageRepository messageRepository;

    @Test
    @Order(1)
    void testFindAllEmpty() {
        assertFalse(messageRepository.findAll().iterator().hasNext());
    }
}

But it doesn't work when I run the test class I got an error Cannot invoke "com.cypherf.repository.MessageRepository.findAll()" because "this.messageRepository" is null. So how are you supposed to do it?

In my main class I have a static main method which instantiates an ApplicationContext then uses it to create a bean and run it:

@ComponentScan
@EnableJpaRepositories
public class TestSpringApplication {
    @Autowired
    private MessageRepository messageRepository;

    public static void main(String[] args) {
        ApplicationContext ctx = new AnnotationConfigApplicationContext(TestSpringApplication.class);
        TestSpringApplication app = ctx.getBean(TestSpringApplication.class);
        app.run(args);
    }

    public void run(String... args) {
        [...]
    }
}

Isthat what I am supposed to do in every test class?


Solution

  • First , you have to use @ExtendWith(SpringExtension.class) to integrate spring testing framework with Junit5.

    Second , you have to use @ContextConfiguration to tell spring what are the configuration classes to use to bootstrap the spring context.

    Not guarantee it would solve all your problems , but combining these two should make your test at least can bootstrap the spring context and autowire MessageRepository into the test class :

    @ExtendWith(SpringExtension.class)
    @ContextConfiguration(classes= TestSpringApplication.class)
    class TestMessageRepository {
    
        @Autowired
        private MessageRepository messageRepository;
    
        @Test
        void testFindAllEmpty() {
            assertFalse(messageRepository.findAll().iterator().hasNext());
        }
    }