java - 用@DataJpaTest 注释的测试不是用@Autowired 注释的 Autowiring 字段

标签 java spring spring-boot spring-data-jpa

我有一个包含 Spring Data Jpa 存储库的 Spring Boot 应用程序。我需要围绕这个存储库运行一个单元(或组件?)测试。我对 Spring Data Jpa 没有很多经验。

这是我的测试。这很简单,我无法通过。

import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import static org.junit.Assert.assertNotNull;

@DataJpaTest
public class FooRepositoryTest {

    @Autowired
    private FooRepository fooRepo;

    @Test
    public void notNull(){
        assertNotNull(fooRepo);
    }
}

这是其他相关的源代码。
import com.fedex.dockmaintenancetool.webservice.types.Foo;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface FooRepository extends JpaRepository<Foo, Long> {
}


import javax.persistence.Entity;

@Entity
public class Foo {
}

我只是想将 Jpa 存储库自动连接到测试中,但我不能。显然,我误解了 Spring Boot 工作方式的一些细微差别。但即使经过一些教程,我也无法弄清楚我错过了什么。有人可以帮我解决这个问题吗?

最佳答案

使用注解时@DataJpaTest ,这意味着您正在尝试仅测试存储库层。该注解用于测试 JPA 存储库,并与 @RunWith(SpringRunner.class) 结合使用启用填充应用程序上下文。 @DataJpaTest注释禁用完全自动配置并仅应用与 JPA 测试相关的配置。所以@fap siggested 使用它,如:

@RunWith(SpringRunner.class)
@DataJpaTest
public class FooRepositoryTest {

    @Autowired
    private FooRepository fooRepo;

    @Test
    public void notNull(){
        assertNotNull(fooRepo);
    }
}

使用注解时@RunWith(SpringRunner.class) SpringRunner 提供对加载 Spring ApplicationContext 和拥有 bean 的支持 @Autowired进入您的测试实例。

关于java - 用@DataJpaTest 注释的测试不是用@Autowired 注释的 Autowiring 字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58634359/

相关文章:

java - 如果程序仅通过 doClick() 进行交互,则 JFrame 永远不会呈现;

java - Android KeyPairGenerator 始终生成相同的 key 对

java - 如何解决spring boot框架的Endless Building process?

java - Autowiring 不起作用,Spring Boot 1.5.8,NoSuchBeanDefinitionException :BCryptPasswordEncoder,

java - 自定义数组列表按位置更改项目

java - Maven 离线 - mvn-plugins 的问题

java - Spring:Bean 属性不可写或具有无效的 setter 方法

java - 在高峰时间,请求在 Tomcat 8 中花费太多时间

java - Spring Security - 无法使用自定义登录页面登录

spring-boot - Spring Cloud Refresh 事件无法识别已删除的属性?