Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Migrating from JUnit4 to JUnit5 throws NullPointerException on @Autowired repositories

I have a very simple repository test, it runs just fine when I'm using JUnit's 4 "@RunWith(SpringRunner.Class)". When I tried to use "@ExtendWith" like in the provided example I get a NullPointerException when trying to work with the repository. It seems like "@Autowire" doesn't inject the repository when using the latter annotation. Here's the pom.xml file and stack trace: https://pastebin.com/4KSsgLfb

Entity Class:

package org.tim.entities;

import lombok.AccessLevel;
import lombok.Data;
import lombok.NonNull;
import lombok.Setter;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.validation.constraints.NotNull;

@Entity
@Data
public class ExampleEntity {

@Id
@Setter(AccessLevel.NONE)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@NotNull
@NonNull
private String name;

}

Repository Class:

package org.tim.repositories;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import org.tim.entities.ExampleEntity;

@Repository
public interface ExampleRepository extends JpaRepository<ExampleEntity, Long> {
}

Test Class:

package org.tim;

import org.junit.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.tim.entities.ExampleEntity;
import org.tim.repositories.ExampleRepository;


@ExtendWith(SpringExtension.class)
@DataJpaTest
public class exampleTestClass {

@Autowired
private ExampleRepository exampleRepository;

@Test
public void exampleTest() {
    exampleRepository.save(new ExampleEntity("name"));
}
}
like image 733
Vash Avatar asked Feb 28 '19 15:02

Vash


2 Answers

You're using the wrong @Test annotation.

When using the SpringExtension and JUnit Jupiter (JUnit 5), you have to use import org.junit.jupiter.api.Test; instead of import org.junit.Test;.

like image 117
Sam Brannen Avatar answered Oct 21 '22 06:10

Sam Brannen


in the documentation it says:

If you are using JUnit 4, don’t forget to also add @RunWith(SpringRunner.class) to your test, otherwise the annotations will be ignored. If you are using JUnit 5, there’s no need to add the equivalent @ExtendWith(SpringExtension) as @SpringBootTest and the other @…Test annotations are already annotated with it.

Testing Spring Boot Applications

So try removing the @extendWith in your testclass

like image 1
Toerktumlare Avatar answered Oct 21 '22 06:10

Toerktumlare