关闭

Gmock初体验

发表于:2009-9-25 17:01

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:未知    来源:51Testing博客转载

  (一)模拟强类型对象

  为什么会出现上面说的那种怪异的情况的?因为groovy的弱类型语言。同样,GMock也同样支持像Java一样的强类型。示例如下:

1. public class StrongTypeTest extends GMockTestCase{ 
2.     @Test 
3.     public void testStrongType(){ 
4.         File mockFile = mock(File, constructor("/a/path/file.txt")) 
5.         mockFile.getName().returns("file.txt") 
6.         play { 
7.           def file = new File("/a/path/file.txt") 
8.           assertEquals "file.txt", file.getName() 
9.         } 
10.     } 
11. } 

  在mock()方法中,接受一个可选参数,也就是需要模拟的类型。同时,如果要模拟的类型需要使用构造函数,则可以通过constructor()来指明构造函数。

  (二)模拟异常类型

  通常情况下,异常类型在单元测试中很难获得。在这里可以使用raises()来模拟异常类型。

1. def loader = mock() 
2. loader.put("throw exception").raises(new RuntimeException("an exception")) // or 'raises(RuntimeException, "an exception")' 
3. play { 
4.     def message = shouldFail(RuntimeException) { 
5.        loader.put("throw exception")  
6.     } 
7.     assertEquals "an exception", message 
8. }

  (三)模拟静态方法调用

  对于静态方法,可以在没有对象的情况下直接使用类名调用,下面就给出示例代码。

1. def mockMath = mock(Math) 
2. mockMath.static.random().returns(0.5) 
3.  
4. play { 
5.    assertEquals 0.5, Math.random() 
6. } 

  (四)模拟构造函数

1. def mockFile = mock(File, constructor("/a/path/file.txt").raises(RuntimeException))
2. play {
3.   shouldFail(RuntimeException) {
4.     new File("/a/path/file.txt")
5.   }
6. }

  之前已经给出了模拟构造函数和模拟异常类型的方法,这里综合使用一下。在构建构造函数时会抛出异常。在play闭包中使用shouldFail来判定。

32/3<123>
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号