我有一个包含 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/