我们的目前有一个相当大的单元测试存储库。单元测试将通用的可重用测试代码重构到TestUtil类中,这些类是@Component注释的。
看来,SpringRunner单元测试用例只能在@Autowired TestUtil类作为@SpringBootTest注释的类参数的一部分导入时才能找到它们。
此外,@Autowired类中的所有TestUtil变量也需要在@SpringBootTest注释的类参数中导入。
由于我们有大约30个单元测试用例类,而且每个类都需要在@SpringBootTest注释中导入大约40个其他类,因此可以想象这是多么难以维护。
如果类未作为@SpringBootTest类参数的一部分导入,则引发以下错误
org.springframework.beans.factory.UnsatisfiedDependencyException:错误创建名为“com.company.FeeTest”的bean :通过字段‘accountTestUtils’表示的不满意的依赖关系;嵌套的异常是org.springframework.beans.factory.NoSuchBeanDefinitionException: No,类型为'com.company.accountTestUtils‘类型的限定bean :预期至少有一个bean可以作为自动测试候选。依赖性注释:{@org.springframework.beans.factory.annotation.Autowired(required=true)}
有没有人知道在单元测试用例中使用@Autowired注释而不必在@SpringBootTest注释中显式导入它们的更好方法?
下面是一个代码示例
FeeTest.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();
...
}
}TransferTest.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发布于 2020-01-15 11:53:38
让我从TransferTest.java类的pov中谈谈。
这个类测试AccountUtilsTest类。因此,只需将AccountUtilTest类的依赖项提供给TransferTest.Mock,每个依赖项都是自动连接的,并在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();
...
}
}https://stackoverflow.com/questions/45942402
复制相似问题