【问题标题】:Autowired repository is null in my @SpringBootTest class我的@SpringBootTest 类中的自动装配存储库为空
【发布时间】:2021-08-12 02:38:26
【问题描述】:

我正在尝试测试我的 GET 端点。为此,我需要在我的内存 H2 数据库中加载一些数据。我有以下测试类:

@ExtendWith(SpringExtension.class)
@SpringBootTest(webEnvironment= SpringBootTest.WebEnvironment.RANDOM_PORT)
public class UserApiControllerIntegrationTest {

    @Autowired
    private ExerciseRepository myRepository;

    ...

    @Before
    public void initializeDatabase() {
        ...
    }
}

initializeDatabase() 方法中,我创建了几个对象并使用存储库方法.saveAndFlush() 将它们保存在我的数据库中。

当我尝试运行这个测试类时,出现以下错误:

java.lang.NullPointerException:无法调用 “....MyRepository.saveAndFlush(Object)”因为“this.myRepository”是 空

我看到一些帖子有相同的错误但没有正确答案。我也尝试输入@DataJpaTest,但没有任何反应。 我也尝试添加@RunWith(SpringRunner.class)注解但是又出现了一个错误:

java.lang.IllegalStateException:配置错误:发现多个 测试类的@BootstrapWith 声明 [com.egym.recruiting.codingtask.api.RankingApiControllerIntegrationTest]: [@org.springframework.test.context.BootstrapWith(值=org.springframework.boot.test.context.SpringBootTestContextBootstrapper), @org.springframework.test.context.BootstrapWith(value=org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTestContextBootstrapper)]

...

更新

这是我的 Application.java 类:

@SpringBootApplication
@ComponentScan(basePackages = { "...", "....api",
        "....config" })
public class Application implements CommandLineRunner {

    public static void main(String[] args) {
        new SpringApplication(Application.class).run(args);
    }

    ...
}

在我的配置目录中:

  • 我启用 swagger2 的 OpenAPIDOcumentationConfig 类
  • 用于重定向到 OpenAPI api 文档的 HomeController 类

我认为这些对我的错误没有影响。

【问题讨论】:

  • 你能发布你的主要弹簧类吗...它的注释和配置也会影响弹簧测试设置。
  • 我会尽快更新

标签: spring-boot junit java-11 spring-test


【解决方案1】:

Spring 注释 @SpringBootTest 将仅扫描在您的文件目录(和子目录)下声明的 bean。为了扫描额外的 bean,您需要像在 SpringBootApplication 类中一样提供带有 @ComponentScan 注释的目录

添加测试配置文件:

@Configuration
@ComponentScan(basePackages = { "...", "....api",
    "....config" })
public class TestConfig {
}

将测试配置文件链接到您的测试类:

@ExtendWith(SpringExtension.class)
@SpringBootTest(webEnvironment= SpringBootTest.WebEnvironment.RANDOM_PORT, 
                classes= TestConfig.class)
public class UserApiControllerIntegrationTest {

    @Autowired
    private ExerciseRepository myRepository;

    ...

    @Before
    public void initializeDatabase() {
        ...
    }
}

【讨论】:

  • 您好 krzysztof K,感谢您的回答。我创建了一个新类TestConfig 等于你的(当然我替换了我隐藏的...。此外,我在@SpringBootTest 注释中添加了类参数。但没有任何改变。但是我确认我的测试类在一个不包含 bean 的测试目录。
【解决方案2】:

我们可以在测试类中创建一个 myrepository bean 实例来连接依赖。

我们可以尝试像 mockito 这样的库来模拟我们测试用例中的 bean。

【讨论】:

  • 您能否更具体一些或提供一些代码/文档?
猜你喜欢
  • 1970-01-01
  • 2021-08-17
  • 2019-04-06
  • 2014-04-22
  • 1970-01-01
  • 2016-08-08
  • 1970-01-01
  • 2015-01-21
  • 2016-08-10
相关资源
最近更新 更多