我是使用Mockito框架(以及行为/测试驱动开发)和使用的新手 帮我编写一些东西;
我正在为xml编写自己的Java库以创建图形内容
我试过首先验证一些行为:
(MockitoAnnotations.initMocks(Class)
)中使用了BaseTestClass
:
public class GeneralXml extends BaseTestClass {
private static final String TAG = "General XML";
@Mock(name="xml") private XmlGraphics mockXML;
@Before
public void setUp() throws Exception{
//stub method parseDimension
when(mockXML.parseDimension(anyString()))
.thenReturn(500);
// stub method parsePosition: 500 X 500 X 500 is an
// arbitrary dimension of window
when(mockXML.parsePosition(anyString()))
.thenReturn(
new Random().nextFloat() * mockXML.parseDimension(Xml.WIDTH),
new Random().nextFloat() * mockXML.parseDimension(Xml.HEIGHT),
new Random().nextFloat() * mockXML.parseDimension(Xml.DEPHT));
// Now Colors must have betwwen 0 and 255
// (RGB color)
when(mockXML.parseColorComponent(anyString()))
.thenReturn(
new Random().nextInt(256),
new Random().nextInt(256),
new Random().nextInt(256));
}
但我在所有后续验证中都收到错误,例如:
@Test
public void mockPosition() {
Log.d(TAG, "mock", "x = "+mockXML.parsePosition(Xml.X));
Log.d(TAG, "mock", "y = "+mockXML.parsePosition(Xml.Y));
Log.d(TAG, "mock", "z = "+mockXML.parsePosition(Xml.Z));
verify(mockXML, times(3)).parsePosition(anyString());
}
我认为我的错误在于:
when(mockXML.parsePosition(anyString()))
.thenReturn(
new Random().nextFloat() * mockXML.parseDimension(Xml.WIDTH),
new Random().nextFloat() * mockXML.parseDimension(Xml.HEIGHT),
new Random().nextFloat() * mockXML.parseDimension(Xml.DEPHT));
这不是有效的代码吗?或者我误解了什么? 谢谢你的帮助
答案 0 :(得分:2)
尝试将其添加为setUp()函数的第一行:
MockitoAnnotations.initMocks(this);