Question

I'm trying to write a unit test for my filters, and I'm struggling to understand the demand for my mocked object. Here is a simple failing test:

void "test my sanity"() {
    setup:
    def vendorPayment = mockFor(Payment)
    vendorPayment.demand.buyerId { -> 123}

    def vp = vendorPayment.createMock()
    //vp.buyerId=123
    println "buyer id: ${vp.buyerId}"

    when:
      def a = "testing"

    then:
      vp.buyerId == 123
}

I wanted to mock the getter for buyerId. Using demand doesn't work, but if I create the mock and then set the buyer id (the commented line), the test will pass. Does demand not work with getters? Is it because the getter is implicitly/dynamically created?

Was it helpful?

Solution

Method getBuyerId has to be mocked. Groovy adds the accessor methods for you in compile time, so method on demand has to be mocked. Take this simple case:

class Payment {
    Integer buyerId
}

Getter/Setter for Payment.groovy will be added when the class is converted to bytecode after compile. Corresponding test would look like:

void "test my power"() {
    setup:
        def vendorPayment = mockFor(Payment)
        vendorPayment.demand.getBuyerId(1..2) { -> 123}

        def vp = vendorPayment.createMock()
        println "buyer id: ${vp.buyerId}"

    expect:
        vp.buyerId == 123

        //This would fail for < 2.3.* because of this bug which is fixed in 2.4
        //http://jira.grails.org/browse/GRAILS-11075
        vendorPayment.verify() //null

}

Note the changes that was made:

  • getBuyerId method is mocked instead of the field buyerId
  • test demands that getBuyerId will be called 1 to 2 times (first while printing, second in then block). By default if nothing is specified, it assumes the method will be called once, which would fail in this case as getBuyerId is invoked twice.
  • We can also verify that the mock control did its job after the test is done
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top