Mockbean包含自动关联

时间:2019-03-06 14:41:41

标签: java spring mockito spring-test

我正在测试一个对bean有依赖性的类。在测试中,我模拟了bean,但是模拟的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;
}

如上所示,模拟的bean包含一个@Autowired依赖项。

对此有任何解决方案,还是我违反了某种测试规则?

当调用模拟bean中的实际方法时,它会调用 myOwnDependencyINeedHereInTheMock ,由于它是模拟bean,因此将为null。

尽管

MockBean在@Autowired类中不是 null ,所以它们可以由Spring Boot找到。

1 个答案:

答案 0 :(得分:0)

也要模拟那个豆子!

    public class testclass {
        @Autowired
        private ClassToTest classToTest;
        @MockBean
        private DependencyOfClassToTest dependencyOfClassToTest;
        @MockBean
        private MyOwnDependencyINeedHereInTheMock myOwnDependencyINeedHereInTheMock;
    }

    public class DependencyOfClassToTest {
        @Autowired
        private MyOwnDependencyINeedHereInTheMock myOwnDependencyINeedHereInTheMock;
    }

更新:下面的测试课程对我有用

@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{

        }


    }
}