我希望类A中的继承的吸气剂返回MyObject的Mock。如何在不直接将A中的getMyObject()方法存根的情况下做到这一点(即通过使用某些MockBase类)?
public class Base {
@Autowired
private MyObject obj;
public MyObject getMyObject(){
return obj;
}
}
public class A extends Base {
@Autowired
private SomeObject xyz;
public void myMethod(){
MyObject obj = getMyObject();
//do something here
}
}
public void MockBase {
@Mock
protected MyObject obj;
public MyObject getMyObject(){
return obj;
}
}
public class ATest extends MockBase {
@InjectMocks
private A a;
@Mock
private SomeObject xyz;
@BeforeMethod
public void setUp(){
MockitoAnnotations.initMocks(this);
}
public void MyMethod_SomeCondition_ExpectedResult{
a.myMethod();
}
}
最佳答案
那里是什么问题?它正在按预期工作,也许您正在使用旧版本的Mockito。例如,版本1.9.5:
这是您要测试的课程的父级:
public class Base {
private BaseObjectDependency base_object_dependency;
public BaseObjectDependency getBase_object_dependency() {
return base_object_dependency;
}
}
这是您要测试的课程:
public class Child extends Base {
private ChildObjectDependency child_object_dependency;
public void myMethod() {
BaseObjectDependency obj = getBase_object_dependency();
//do something here
}
public ChildObjectDependency getChild_object_dependency() {
return child_object_dependency;
}
}
这里是依赖项:
public class BaseObjectDependency { }
public class ChildObjectDependency { }
现在是测试的父类:
import org.mockito.Mock;
public class MockBase {
@Mock protected BaseObjectDependency base_test_dependency_mock;
}
最后是测试:
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
public class ChildTest extends MockBase {
@InjectMocks private Child child;
@Mock private ChildObjectDependency child_test_dependency_mock;
@BeforeClass
public void setUp() {
MockitoAnnotations.initMocks(this);
}
@Test
public void check_that_mocks_are_correctly_injected() {
assertNotNull(child.getBase_object_dependency());
assertEquals(base_test_dependency_mock, child.getBase_object_dependency());
assertNotNull(child.getChild_object_dependency());
assertEquals(child_test_dependency_mock, child.getChild_object_dependency());
}
}
您会看到我在任何地方都没有对
getBase_object_dependency()
进行存根。