(一)模拟强类型对象
为什么会出现上面说的那种怪异的情况的?因为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来判定。