[英]Test annotated with @DataJpaTest not autowiring field annotated with @Autowired
我有一个 Spring 引导应用程序,其中包含一个 Spring 数据 Jpa 存储库。 我需要围绕这个存储库运行一个单元(或组件?)测试。 我对 Spring 数据 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 如何工作的一些细微差别。 但即使经过一些教程,我也无法弄清楚我错过了什么。 谁能帮我解决这个问题?
您缺少@RunWith(SpringRunner.class)
注释,它告诉 JUnit 实际启动 Spring 应用程序进行测试。
您的测试 class 应该看起来像
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.assertNotNull;
@RunWith(SpringRunner.class)
@DataJpaTest
public class FooRepositoryTest {
@Autowired
private FooRepository fooRepo;
@Test
public void notNull(){
assertNotNull(fooRepo);
}
}
问题中使用的 JUnit 版本仍然是 JUnit 4. Spring Boot 2.2.0 切换到 JUnit5。
使用 JUnit5,您必须使用@ExtendWith(SpringExtension.class)
而不是@RunWith(SpringRunner.class)
。
当您使用注释@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
放入您的测试实例中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.