问题描述
我有一个非常简单的存储库测试,当我使用它时,它运行得很好JUnit的4个"@RunWith(SpringRunner.Class)".当我尝试使用提供的示例中的"@ExtendWith"时,尝试使用存储库时出现NullPointerException.使用后一个注解时,似乎"@Autowire"不会注入存储库.这是pom.xml文件和堆栈跟踪: https://pastebin.com/4KSsgLfb
I have a very simple repository test, it runs just fine when I'm usingJUnit'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
实体类:
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;
}
存储库类:
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> {
}
测试类:
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"));
}
}
推荐答案
您使用了错误的@Test
注释.
使用SpringExtension
和JUnit Jupiter(JUnit 5)时,必须使用import org.junit.jupiter.api.Test;
而不是import org.junit.Test;
.
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;
.
这篇关于从JUnit4迁移到JUnit5会在@Autowired存储库上引发NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!