Ernesto Vargas
Ernesto Vargas

Reputation: 11

Grails Test mockFor java.util.Calendar.getInstance()

I am trying to mock a Calendar on grails 2.2.2 unit test using grails.test.mixin .mockFor but I have the following error: No more calls to 'getInstance' expected at this point. End of demands. Does anyone know if this is possible to mock Calendar?

The test class: @TestFor(FechaService) class FechaServiceTests {

void testGetMesesCrearMetrica() {
    given:
    def cal = Calendar.getInstance().set(Calendar.MONTH, 0)
    def mockCalendar = mockFor(Calendar)
    mockCalendar.demand.static.getInstance{-> cal}
    mockCalendar.createMock()
    when:
    def meses = service.getMesesCrearMetrica()
    ...
}

}

The service method: def getMesesCrearMetrica(){ def meses = [:]

    for(def mes : Meses.values()){
        if(mes.value -1 == Calendar.getInstance().get(Calendar.MONTH)) break
        meses[mes.value] = mes.name()
    }
    return meses
}

Upvotes: 1

Views: 129

Answers (1)

Ian Stride
Ian Stride

Reputation: 157

You could change the signature of the method under test so that it accepts a Calendar as an argument.

Failing that, I would also try using metaClass.

@ConfineMetaClassChanges(Calendar)
void testGetMesesCrearMetrica() {
    given:
    def cal = Calendar.getInstance()
    cal.set(Calendar.MONTH, 0)
    Calendar.metaClass.static.getInstance = { cal }

    when:
    def meses = service.getMesesCrearMetrica()
    ...
}

Upvotes: 0

Related Questions