home | career | drupal | java | mac | mysql | perl | scala | uml | unix

Groovy example source code file (StubTest.groovy)

This example Groovy source code file (StubTest.groovy) is included in the DevDaily.com "Java Source Code Warehouse" project. The intent of this project is to help you "Learn Java by Example" TM.

Java - Groovy tags/keywords

company, duke, groovytestcase, intercepted, intercepted, objectgraphbuilder, speaker, speaker, starting, string, string, stubfor, stubfor, stubtest

The Groovy StubTest.groovy source code

package groovy.mock.interceptor

class StubTest extends GroovyTestCase {

   void testBehaviorWithInstanceCreatedOutsideUseClosure() {
      def speakerStub = new StubFor(Speaker)
      speakerStub.demand.startLecture() { "Intercepted!" }

      def speaker1 = new Speaker()
      assert speaker1.startLecture() == "Starting..."

      speakerStub.use {
         def speaker2 = new Speaker()
         assert speaker2.startLecture() == "Intercepted!"
      }

      speakerStub.demand.startLecture() { "Intercepted!" }
      speakerStub.use (speaker1) {
         assert speaker1.startLecture() == "Intercepted!"
      }
      assert speaker1.startLecture() == "Starting..."
   }

   void testWIthOGBOutsideUse() {
      def ogb = new ObjectGraphBuilder( classNameResolver: 'groovy.mock.interceptor' )
      def stub = new StubFor( Company )
      stub.demand.payroll(0..2) { 500 }
      def acme = ogb.company {
         employee( name: 'Duke', salary: 42 )
      }
      stub.use (acme) {
         assert acme.payroll() == 500
         assert acme.payroll() == 500
      }
   }

   void testWIthOGBInsideUse() {
      def ogb = new ObjectGraphBuilder( classNameResolver: 'groovy.mock.interceptor' )
      def stub = new StubFor( ObjectGraphBuilder )
      stub.use {
         def acme = ogb.company {
            // blows after the next line because property handling
            // on Company was not demanded
            employee( name: 'Duke', salary: 42 )
         }

         def stub2 = new StubFor( Company )
         stub2.demand.payroll(0..2) { 500 }
         stub2.use (acme) {
           assert acme.payroll() == 500
         }
      }
   }

}

class Speaker {
   String name
   def startLecture() { "Starting..." }
}


class Company {
   String name
   List employees = []
   def payroll() {
      def total = 0
      employees.each { total += it.salary }
      total
   }
}

class Employee {
   String name
   Number salary = 0
}

Other Groovy examples (source code examples)

Here is a short list of links related to this Groovy StubTest.groovy source code file:

new blog posts

 

Copyright 1998-2014 Alvin Alexander, alvinalexander.com
All Rights Reserved.