groovy

Add ability to mock/stub constructors

Details

  • Type: Improvement Improvement
  • Status: Closed Closed
  • Priority: Minor Minor
  • Resolution: Fixed
  • Affects Version/s: 1.0
  • Fix Version/s: 1.7.1
  • Component/s: mocks and stubs
  • Labels:
    None
  • Environment:
    groovy 1.0, Java 1.5, Windows 2000
  • Number of attachments :
    1

Description

Would like the ability to stub/mock constructors.

Example:

def dateStub = new StubFor( Date )

dateStub.demand.Date{ aControlCurrentTime }

Expectation is that .Date would be the default constructor of the Date class.

Activity

Hide
Paul King added a comment -

I have a minor modification to MockFor/StubFor which supports this functionality. Here is an example of usage (mirroring this issue's suggestion):

import groovy.mock.interceptor.MockFor
class Person {
  String first, last
}
def interceptConstructorCalls = true
def mock = new MockFor(Person, interceptConstructorCalls)
def dummy = new Person(first:'Tom', last:'Jones')
mock.demand.with {
  Person() { dummy } // expect constructor call, return dummy
  getFirst() {'John'}
  getLast() {'Doe'}
}
mock.use {
  def p = new Person(first:'Mary', last:'Smith')
  assert p.first == 'John'
  assert p.last == 'Doe'
}

There is an optional parameter (defaulting to false) for the Constructor which indicates that mocking of the constructor is to be enabled. It is only possible to use with GroovyObjects.

Show
Paul King added a comment - I have a minor modification to MockFor/StubFor which supports this functionality. Here is an example of usage (mirroring this issue's suggestion):
import groovy.mock.interceptor.MockFor
class Person {
  String first, last
}
def interceptConstructorCalls = true
def mock = new MockFor(Person, interceptConstructorCalls)
def dummy = new Person(first:'Tom', last:'Jones')
mock.demand.with {
  Person() { dummy } // expect constructor call, return dummy
  getFirst() {'John'}
  getLast() {'Doe'}
}
mock.use {
  def p = new Person(first:'Mary', last:'Smith')
  assert p.first == 'John'
  assert p.last == 'Doe'
}
There is an optional parameter (defaulting to false) for the Constructor which indicates that mocking of the constructor is to be enabled. It is only possible to use with GroovyObjects.
Hide
Paul King added a comment -

Proposed patch - planning to apply to trunk once I have written some tests.

Show
Paul King added a comment - Proposed patch - planning to apply to trunk once I have written some tests.
Hide
Paul King added a comment -

Fixed in trunk.

Show
Paul King added a comment - Fixed in trunk.

People

Vote (5)
Watch (8)

Dates

  • Created:
    Updated:
    Resolved: