0

我无法让它工作。就像方法没有被嘲笑一样。

是否有替代的 groovy 测试框架可以更好地模拟静态 Java 方法?

2011 年 3 月 2 日更新:添加代码:

我实际上是在尝试模拟 Scala XML.loadXml(我正在尝试使用 Groovy 进行单元测试)类:

这是我的测试用例:

// ContentManagementGatewayTest.groovy
class ContentManagementGatewayTest extends GMockTestCase
{
  void testGetFileList()
  { 
      // Preparing mocks code will go here, see below

      play {
           GetFileGateway gateway = new GetFileGateway();
           gateway.getData();
      }
  }
}

// GetFileGateway.scala
class GetFileGateway {
    def getData() 
    {  
         // ...
         val xmlData = XML.loadData("file1.txt");
    }
}

我尝试使用 gmock 和 metaClass 进行测试:

// metaClass:
XML.metaClass.'static'.loadFile = {file ->
      return "test"
}

// gmock:
def xmlMock = mock(XML)
xmlMock.static.loadFile().returns(stream.getText())
4

3 回答 3

3

You can do this using Groovy (metaprogramming), you don't need any additional libraries. Here's a (stupid) example, that overrides Collections.max such that it always returns 42. Run this code in the Groovy console to test it.

// Replace the max method with one that always returns 42
Collections.metaClass.static.max = {Collection coll ->
  return 42
}  

// Test it out, if the replacement has been successful, the assertion will pass
def list = [1, 2, 3]
assert 42 == Collections.max(list)

Update

You mentioned in a comment that my suggestion didn't work. Here's another example that corresponds to the code you've shown in your question. I've tested it in the Groovy console and it works for me. If it doesn't work for you, tell me how your testing differs from mine.

Math.metaClass.static.random = {-> 0.5}
assert 0.5 == Math.random()
于 2011-03-02T09:57:51.833 回答
2

Scala 没有静态方法,所以难怪你不能模拟一个——它不存在。

您引用的方法loadXmlXML 对象上找到。您可以使用 来从 Java 中获取该对象scala.XML$.MODULE$,但是,由于对象是单例的,因此它的类是最终的。

唉,是在对象扩展loadXML的类上定义的,而不是在对象本身上。因此,您可以简单地对. 它将缺少一些方法,但也许它会满足您的所有需求。XMLLoaderXMLXMLXMLLoader

于 2011-03-02T13:50:05.093 回答
2

GMock的文档似乎表明您可以这样做:

模拟静态方法调用和属性调用与标准方法调用类似,只需添加 static 关键字即可:

def mockMath = mock(Math)
mockMath.static.random().returns(0.5)

play {
  assertEquals 0.5, Math.random()
}
于 2011-03-02T10:23:20.960 回答