从JUnit4迁移到JUnit5会在@Autowired存储库上引发NullPointerException [英] Migrating from JUnit4 to JUnit5 throws NullPointerException on @Autowired repositories

查看:346
本文介绍了从JUnit4迁移到JUnit5会在@Autowired存储库上引发NullPointerException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的存储库测试,当我使用它时,它运行得很好 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 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

实体类:

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆