java mock 测试

当我们在做一个大型的项目时,往往需要很多人的共同开发, 这就带来一个问题, 有可能你写的代码部分需要依赖于其他人的代码, 比如有一个Computer接口,

interface Computer {
    int boot();
    int reboot();
    int shutdown();
    String getName();
}

这个是其他要实现的, 但我的代码需要调用, 总不能等他把代码拷过来,再测试吧。

如果不用mock,则我们需要自己写一个实类,实现Computer接口, 然后才能测试.

有了mock一切都变得简单多了。

他能虚拟一个Computer 对象,结果由我们自己控制,便于我们测试。

import static org.mockito.Mockito.*;
interface Computer {
    int boot();
    int reboot();
    int shutdown();
    String getName();
}
class Test {

    public static void main(String[] args) {
        Computer computer = mock(Computer.class);
        when(computer.boot()).thenReturn(0); /* 当我们调用boot时返回0 */
        when(computer.shutdown()).thenThrow(new RuntimeException("Undefined!")); /* 当调用shutdown时抛出异常 */
        computer.boot();
        computer.shutdown();
        verify(computer).boot(); /* 测试boot是否被执行 */
    }
}

我们也可以根据已有的对象生成一个mock对象,用spy方法即可,比如我们有一个computer对象, 我们想控制它, 则可以这样调用Computer spyComputer = spy(computer).

当然mock的方法远远不止这些, 更多东西还是参考官方文档吧.

posted @ 2013-07-16 16:02  int32bit  阅读(236)  评论(0)    收藏  举报