如何在Mockito中模拟Spring依赖项 [英] How to mock Spring dependencies in mockito

查看:176
本文介绍了如何在Mockito中模拟Spring依赖项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试模拟Spring Beans.我能够模拟对象B和C.但是无法模拟类B中的对象. 插入类A的模拟包含B.但是即使我嘲笑了它们,X和Y还是为空. Mockito中有什么方法可以模拟Spring bean中member成员的Objects.

I am trying to mock Spring Beans. I am able to Mock object B and C. But am not able to Mock the object inside class B. The mock that is inserted in class A contains B . but X and Y are null even though i have mocked them. is there any way in Mockito to mock the Objects of member of member inside the Spring bean.

@Named
@Scope(value = "prototype")
public class A {        
    @Inject
    private B b;
    @Inject
    private C c;        
}

@Named
@Scope(value = "prototype")
public class B {        
    @Inject
    private X x;
    @Inject
    private Y y;        
}

我需要在其中填充类A的所有依赖项的测试类.

The Testing Class in which i need to populate all the dependencies of Class A.

@RunWith(MockitoJUnitRunner.class)
public class ATest {     

    @InjectMocks
    A a = new A();    

    @Mock
    private B b;
    @Mock
    private C c;

    @Mock
    private X x;
    @Mock
    private Y y;
}

推荐答案

您可以下一步.在这种情况下,B将成为间谍对象,因此您可以根据需要模拟方法结果.或者,您可以将真实的B方法与模拟的X和Y方法结合使用.

You can do next. In this case, B will be spy object so you can mock methods results on it if needed. Or you can use real B methods with mocked X and Y methods.

    @RunWith(MockitoJUnitRunner.class)
public class ATest {        

    @Mock
    private X x;
    @Mock
    private Y y;


        @Spy
        @InjectMocks
        private B b;

        @Mock
        private C c;

        @InjectMocks
        A a; 

        @Before
        public void setUp() {
           MockitoAnnotations.initMock(this);
        }

    }

这篇关于如何在Mockito中模拟Spring依赖项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆