我希望A类中继承的getter返回Mock of MyObject。如果不直接在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();
}
}
答案 0 :(得分:1)
那里有什么问题?它按预期工作,也许你使用旧版Mockito。例如,版本1.9.5:
Heres是您要测试的班级的父级:
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()
。