Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I get a groovy MockFor/StubFor ignore method to use a demand method

Below is the behavior I am seeking. I want a Groovy MockFor ignore method to call a demand method, instead of the ignore method calling the dontIgnoreMe() method directly.

Essentially, I want to replace dontIgnoreMe() me with a mock, and have ignoreMe() call the mock (which I have done with metaClass) It appears like categories might be a better solution. I'll look into that next week, see: groovy nabble feed

import groovy.mock.interceptor.MockFor

class Ignorable {
    def dontIgnoreMe() { 'baz' }
    def ignoreMe() { dontIgnoreMe() }
}

def mock = new MockFor(Ignorable)
mock.ignore('ignoreMe')
mock.demand.dontIgnoreMe { 'hey' }

mock.use {
    def p = new Ignorable()
    assert p.dontIgnoreMe() == 'hey'
    assert p.ignoreMe() == 'hey'
}

Assertion failed: 

assert p.ignoreMe() == 'hey'
       | |          |
       | baz        false
       Ignorable@6879c0f4
like image 902
coderextreme Avatar asked Nov 13 '22 10:11

coderextreme


1 Answers

For groovy developers I strongly recommend Spock Framework!

Use Spy like in the code below:

def "Testing spy on real object with spock"() {
    given:
    Ignorable ignorable = Spy(Ignorable)
    when:
    ignorable.dontIgnoreMe() >> { 'hey' }
    then:
    ignorable.ignoreMe() == 'hey'
    ignorable.dontIgnoreMe() == 'hey'
}
like image 166
rafaelim Avatar answered May 25 '23 02:05

rafaelim