2

我是使用 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));

这不是一个有效的代码?还是我误解了什么?谢谢你的帮助

4

1 回答 1

3

尝试将此添加为 setUp() 函数的第一行:

    MockitoAnnotations.initMocks(this);
于 2011-08-24T15:30:04.893 回答