javascalagroovygmock

Can gmock mock static methods of Java classes? Alternative?


I could not get it to work. It's like the method is not mocked.

Are there alternative groovy testing frameworks that work better to mock static Java methods?

Update 02/Mar/2011: Adding code:

I am actually trying to mock the Scala XML.loadXml (I am trying Groovy for unit testing) class:

This is my test case:

// 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");
    }
}

I tried testing using both gmock and metaClass:

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

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

Solution

  • Scala doesn't have static methods, so it is no wonder you couldn't mock one -- it doesn't exist.

    The method loadXml to which you refer is found on the XML object. You can get that object from Java with scala.XML$.MODULE$, but, since objects are singleton, its class is final.

    Alas, loadXML is defined on the class XMLLoader, which the object XML extends, not on the object XML itself. So you can simply do a normal mock of XMLLoader. It will lack a few methods, but perhaps it will do all you need.