我记得读过一个例子,展示了如何设置模拟对象的成员,例如:
MyClass mockedClass = mock(MyClass.class);
//and something like this to set `someVariable` with some value
Mokito.set(mockedClass.someVariable, actual_value_intended_to_be_set);
不幸的是,我无法再次找到该链接。有人能尊敬这样的例子还是在这里解释?
如果您希望mock的外部行为看起来像mockedClass.someVariable具有actual_value_intend_to_be_set,您可以编写:
when(mockedClass.getSomeVariable()).thenReturn(actual_value_intended_to_be_set);
嘲笑快乐!
这可能是您想要的吗?
public class MyClassTest {
@InjectMocks private MyClass mockedClass;
@BeforeMethod(groups = { "unit" })
public void setup() throws Exception {
mockedClass = new MyClass();
MockitoAnnotations.initMocks(this);
Mockito.when(getSomeVariable()).thenReturn(actual_value_intended_to_be_set);
}
@Test(groups = { "unit" })
public void testMyClass() throws Exception {
//almost too trivial an example since you just setup this.
Assert.assertEquals(getSomeVariable(), actual_value_intended_to_be_set);
}
}
它创建MyClass
对象,sets
也是返回值。