Migrating from JUnit4 to JUnit5 throws NullPointerException on @Autowired repositories

北城余情 提交于 2019-12-08 01:12:25

问题


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"));
}
}

回答1:


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;.




回答2:


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



来源:https://stackoverflow.com/questions/54928869/migrating-from-junit4-to-junit5-throws-nullpointerexception-on-autowired-reposi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!