【问题标题】:Migrating from JUnit4 to JUnit5 throws NullPointerException on @Autowired repositories从 JUnit4 迁移到 JUnit5 会在 @Autowired 存储库上引发 NullPointerException
【发布时间】:2019-07-22 13:20:40
【问题描述】:

我有一个非常简单的存储库测试,它在我使用时运行良好 JUnit 的 4“@RunWith(SpringRunner.Class)”。当我尝试像在提供的示例中那样使用“@ExtendWith”时,在尝试使用存储库时会收到 NullPointerException。使用后一个注释时,“@Autowire”似乎没有注入存储库。这是 pom.xml 文件和堆栈跟踪: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"));
}
}

【问题讨论】:

  • 你的 pom.xml 是什么样的,你引入了哪些 junit5 依赖项?
  • @ThomasAndolf 我已经添加了 pom.xml 文件的片段。
  • 您能否提供一个最小、完整且可验证的示例stackoverflow.com/help/mcve
  • @SamBrannen 我添加了缺失的类,希望这是一个合适的例子
  • 是的,这就是我想看到的。您使用了错误的 @Test 注释。

标签: maven spring-boot junit5


【解决方案1】:

您使用了错误的@Test 注释。

使用SpringExtension 和JUnit Jupiter (JUnit 5) 时,您必须使用import org.junit.jupiter.api.Test; 而不是import org.junit.Test;

【讨论】:

  • 很好地抓住了山姆!
【解决方案2】:

在文档中说:

如果您使用的是 JUnit 4,请不要忘记将 @RunWith(SpringRunner.class) 也添加到您的测试中,否则注释将被忽略。如果您使用的是 JUnit 5,则无需将等效的 @ExtendWith(SpringExtension) 添加为 @SpringBootTest 并且其他 @…Test 注释已使用它进行注释。

Testing Spring Boot Applications

所以尝试在你的测试类中删除@extendWith

【讨论】:

  • 我已经尝试删除它并将“@DataJpaTest”更改为“@SpringBootTest”,但没有成功。
猜你喜欢
  • 2018-02-23
  • 2021-08-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-19
  • 2012-08-10
  • 1970-01-01
相关资源
最近更新 更多