Issue Details (XML | Word | Printable)

Key: GROOVY-1823
Type: Improvement Improvement
Status: Resolved Resolved
Resolution: Fixed
Priority: Minor Minor
Assignee: Paul King
Reporter: David Weiler-Thiessen
Votes: 5
Watchers: 8
Operations

If you were logged in you would be able to see more operations.
groovy

Add ability to mock/stub constructors

Created: 09/Apr/07 09:56 AM   Updated: Sunday 07:02 AM   Resolved: Sunday 07:02 AM
Return to search
Component/s: mocks and stubs
Affects Version/s: 1.0
Fix Version/s: 1.7.1

Time Tracking:
Not Specified

File Attachments: 1. Text File GROOVY-1823__Add_ability_to_mock_stub_constructors.patch (5 kB)

Environment: groovy 1.0, Java 1.5, Windows 2000


 Description  « Hide

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.



Paul King added a comment - 03/Feb/10 05:10 AM

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.


Paul King added a comment - 03/Feb/10 05:14 AM

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


Paul King added a comment - 07/Feb/10 07:02 AM

Fixed in trunk.