How to mock the 'new' operator

constructor, grails, groovy, mocking, testing

Solution

The second, optional parameter to `MockFor`'s constructor is `interceptConstruction`. If you set this to true, you can mock the constructor. Example:

import groovy.mock.interceptor.MockFor
class SomeClass {
    def prop
    SomeClass() {
        prop = "real"
    }
}

def mock = new MockFor(SomeClass, true)
mock.demand.with {
    SomeClass() { new Expando([prop: "fake"]) }
}
mock.use {
    def mockedSomeClass = new SomeClass()
    assert mockedSomeClass.prop == "fake"
}

Note, however, you can only mock out groovy objects like this. If you're stuck with a Java library, you can pull the construction of the Java object into a factory method and mock that.

Problem

I'm testing some groovy code that uses a java library and I want to mock out the library calls because they use the network. So the code under test looks something like: ``` def verifyInformation(String information) { def request = new OusideLibraryRequest().compose(information) new OutsideLibraryClient().verify(request) } ``` I tried using MockFor and StubFor but I get errors such as: ``` No signature of method: com.myproject.OutsideLibraryTests.MockFor() is applicable for argument types: (java.lang.Class) values: [class com.otherCompany.OusideLibraryRequest] ``` I'm using Grails 2.0.3.

Original source