如何在测试方法中使用@Autowired

Posted

技术标签:

【中文标题】如何在测试方法中使用@Autowired【英文标题】:how to use @Autowired in the test methods 【发布时间】:2017-03-05 12:18:39 【问题描述】:

我无法在测试方法中使用 Spring 的 @Autowired 注释。我正在使用 JUnit 进行测试。 @Autowiring 适用于 bean 中的普通类,但不适用于测试方法。正如我在论坛中看到的,我必须在 pom.xml 中实现 spring-test。我仍然无法自动连接和注入我的服务 bean 的依赖项。您能否帮我在测试类中使用依赖注入,因为我在源类中使用依赖注入。

问候 阿尔珀

【问题讨论】:

您需要以与运行应用程序时类似的方式设置测试上下文。关于docs.spring.io/spring/docs/3.2.x/spring-framework-reference/… 的信息很多,但简而言之,您应该使用@ContextConfiguration 和@RunWith(SpringJUnit4ClassRunner.class)。另请参阅***.com/questions/2862888/… 抱歉,我没有时间完整回答。顺便说一句,我没有对你投反对票。 【参考方案1】:

如果您正在编写单元测试,建议您使用@Mock@InjectMocks

你可以用MockitoJUnitRunner注释你的测试类来运行

@RunWith(MockitoJUnitRunner.class)
public class TestClass
  @Mock
  private MockedClass;
  @InjectMocks
  private TestedClass;

但是如果你真的想测试所有的流程并且需要注入类,你可以@RunWith(SpringJUnit4ClassRunner.class)@Autowired你的类。


更新:

尝试在你的spring boot应用中添加这个依赖(不需要添加版本)来使用SpringJUnit4ClassRunner

groupId: org.springframework.boot 
artifactId: spring-boot-starter-test 
scope: test 
version: 1.4.4

【讨论】:

你好佩德罗索。当我添加 @RunWith(SpringJUnit4ClassRunner.class) 时,我遇到了 java.lang.NoClassDefFoundError: org/springframework/transaction/TransactionDefinition。 尝试在你的spring boot应用上添加这个依赖(不需要添加版本):groupId: org.springframework.boot artifactId: spring-boot-starter-test scope: test version: 1.4.4

以上是关于如何在测试方法中使用@Autowired的主要内容,如果未能解决你的问题,请参考以下文章

Spring @AutoWired实现原理

[@ MockBean和@Autowired在一个测试类中使用同一服务

Autowired 注解详解

在春天开机使用@Autowired注解的接口

仅使用 @Component 和 @Autowired 使用 SpringJUnit4ClassRunner 进行单元测试

在 kotlin 的 springboot 测试中使用和不使用 @Autowired Constructor 有啥区别