Grails Spock Mock Injected Service in Unit Test

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

How do I inject another service in a Grails UnitTest (Specification) using Spock?

class ServiceOne {

   ServiceTwo serviceTwo

    ModelOne getMethodOne(String name) {
       // do somethings here
       return serviceTwo.getMethodTwo(name)
    }
}

class ServiceTwo {

   ServiceTwo serviceTwo

    ModelOne getMethodTwo(String name) {
       // do somethings here
       return ModelOne.get(name)
    }
}

// Tests
import grails.test.mixin.Mock
import grails.test.mixin.TestFor
import spock.lang.Specification
/**
 * Tests for ServiceOne
 */
@TestFor(ServiceOne)
@Mock(ModelOne)
class ServiceOneSpec extends Specification {
/** Inject serviceTwo in here
    Otherwise the following exception is thrown
    java.lang.NullPointerException: Cannot invoke method getMethodTwo() on null object
*/

void "test method one"() {

    when:
    ModelOne modelOne = service.getMethodOne(name)

    then:
    modelOne != null
   }
}

Answers

Off the top of my head, this should get you started.

@TestFor(ServiceOne)
@Mock(ModelOne)
class ServiceOneSpec extends Specification {

   void "test method one"() {
      given:
         def mockServiceTwo = mockFor(ServiceTwo)
         // expect that getMethodTwo is called once
         mockServiceTwo.demand.getMethodTwo(1) { String name ->
            // for any arbitrary name value, return a new ModelOne
            return new ModelOne()
         }
         service.serviceTwo = mockServiceTwo.createMock()
      when:
         ModelOne modelOne = service.getMethodOne(name)

      then:
         modelOne != null
   }
}

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/37134115/grails-spock-mock-injected-service-in-unit-test

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils