groovygrailsspock

How to use database methods in grails spock specification tests?


I am going to test some classes test using specification test with spock. Some methods uses Domain.list() and it not available via light specification test. Of course I could replace Domain.list() with mock grobal replace. But it disables other Domain static methods. How to change only one static domain method and stay others?

I used mocking this way:

GroovyMock(Domain,global: true)
Domain.list() >> [ domain1, domain2 ]

Solution

  • Have you tried a GroovySpy?

    package de.scrum_master.stackoverflow.q78963473
    
    import spock.lang.Specification
    
    class MockSingleStaticMethodTest extends Specification {
      def test() {
        given:
        GroovySpy(Domain, global: true)
        Domain.list() >> ['domain1', 'domain2']
    
        expect:
        Domain.list() == ['domain1', 'domain2']
        Domain.doSomething() == 'result'
      }
    }
    
    class Domain {
      static List list() {
        println 'listing'
        ['one', 'two', 'three']
      }
    
      static String doSomething() {
        println 'doing something'
        'result'
      }
    }
    

    Try it in the Groovy Web Console.