@Autowired inside SpringRunner SpringBootTest Unit Test Case



我们的Spring Boot REST API目前有一个相当大的单元测试仓库。单元测试将常见的可重用测试代码重构为@Component注释的TestUtil类。

似乎SpringRunner单元测试用例只有在作为@SpringBootTest注释的类参数的一部分导入时才能找到@Autowired TestUtil类。

此外,TestUtil类中的所有@Autowired变量也需要导入到@SpringBootTest注释的 classes 参数中。

由于我们有大约 30 个单元测试用例类,每个类需要在@SpringBootTest注解中导入大约 40 个其他类,因此可以想象这变得多么不可维护。

如果类未作为@SpringBootTest类参数的一部分导入,则会引发以下错误

org.springframework.beans.factory.UnsatisfiedDependencyException: 创建名为"com.company.FeeTest"的 Bean 时出错:不满意 通过字段"帐户测试实用程序"表示的依赖性;嵌 套 例外情况是 org.springframework.beans.factory.NoSuchBeanDefinitionException: No 提供类型为"com.company.accountTestUtils"的合格 bean: 预计至少有 1 个 Bean 符合自动连线候选条件。 依赖项注释: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

有没有人知道在单元测试用例中使用@Autowired注释的更好方法,而不必将它们显式导入@SpringBootTest注释中?

下面是一个代码示例

费用测试.java

package com.company;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {
AccountTestUtils.class,
... need to list any @Autowired component in AccountTestUtils
})
public class FeeTest {
@Autowired
private AccountTestUtils accountTestUtils;
@Test
public void basicFeeTestExpectSuccess() {
accountTestUtils.createAccount();
...
}
}

转学测试.java

package com.company;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {
AccountTestUtils.class,
... need to list any @Autowired component in AccountTestUtils
})
public class TransferTest {
@Autowired
private AccountTestUtils accountTestUtils;
@Test
public void basicTransferTestExpectSuccess() {
accountTestUtils.createAccount();
...
}
}

AccountTestUtils.java

package com.company;
@Component
public class AccountTestUtils {
@Autowired
private IService1 someService1;
@Autowired
private IService2 someService2;
@Autowired
private SomeRepository someRepository1;
public void createAccount() {
someService1.doSomething();
someService2.doSomething();
someRepository2.doSomething();
}
}    

我们的包结构是常见的 maven 结构

/src
/main
/java
/resources
/test
/java
/resources

让我从TransferTest.java类的pov开始谈谈。

此类测试 AccountUtilsTest 类。因此,只需向 TransferTest 提供 AccountUtilTest 类的依赖项,模拟每个自动连线并在 AcccountUtilsTest 中使用的依赖项。

例如:

package com.company;
@RunWith(SpringRunner.class)
public class TransferTest {
@Mock
IService1 someService1Mock;
@Mock
IService2 someService2Mock

@InjectMocks
private AccountTestUtils accountTestUtils;
@Test
public void basicTransferTestExpectSuccess() {
accountTestUtils.createAccount();
...
}
}

最新更新