如何在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);
}
}