我正在测试一个与bean相关的类。在测试中,我嘲笑豆子,但模拟的豆也具有自己的@Autowired
依赖关系。无论如何,我是否可以满足这种依赖性?如今,@Autowired
依赖关系为 null 当称为模拟中的方法时。
示例:
public class testclass {
@Autowired
private ClassToTest classToTest;
@MockBean
private DependencyOfClassToTest dependencyOfClassToTest;
@Mockbean
private MyOwnDependencyINeedHereInTheMock myOwnDependencyINeedHereInTheMock;
}
public class DependencyOfClassToTest {
@Autowired
private MyOwnDependencyINeedHereInTheMock myOwnDependencyINeedHereInTheMock;
}
如上图所示,模拟的豆包含 @Autowired
依赖关系。
对此的任何解决方案还是我打破某种测试规则?
当调用模拟豆中的实际方法时,它会调用 myownependendendenceNedineDhereInthemock ,这将是无效的,因为它是无名的。
无知者不是 null 在@Autowired
类中,因此可以通过Spring Boot找到它们。
也模拟那个豆!
public class testclass {
@Autowired
private ClassToTest classToTest;
@MockBean
private DependencyOfClassToTest dependencyOfClassToTest;
@MockBean
private MyOwnDependencyINeedHereInTheMock myOwnDependencyINeedHereInTheMock;
}
public class DependencyOfClassToTest {
@Autowired
private MyOwnDependencyINeedHereInTheMock myOwnDependencyINeedHereInTheMock;
}
update :下面的测试类适合我
@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationTests {
@Autowired
private ClassToTest classToTest;
@MockBean
private DependencyOfClassToTest dependencyOfClassToTest;
@MockBean
private MyOwnDependencyINeedHereInTheMock myOwnDependencyINeedHereInTheMock;
@Test
public void contextLoads() {
System.out.println("test"+myOwnDependencyINeedHereInTheMock);
}
@TestConfiguration
static class Context{
@Component
static class ClassToTest{
@Autowired
private DependencyOfClassToTest dependencyOfClassToTest;
}
@Component
static class DependencyOfClassToTest{
@Autowired
private MyOwnDependencyINeedHereInTheMock myOwnDependencyINeedHereInTheMock;
}
@Component
static class MyOwnDependencyINeedHereInTheMock{
}
}
}