Forgus / spock

Automatically exported from code.google.com/p/spock
0 stars 0 forks source link

Enable spying of private methods #281

Closed GoogleCodeExporter closed 8 years ago

GoogleCodeExporter commented 8 years ago
Spy with mocked public methods are allowed and working flawlessly. It would be 
great if we can mock private methods on Spies since that is common scenario 
during partial mocking.

For example in code below, test passes if getDefaultPlusOne() is public, but 
fails if it is private.

    class ClassUnderTest {
        public int getDefault() {
            0
        }

        private int getDefaultPlusOne() {
            getDefault() + 1
        }
    }

      def "let's try this!"() {
        when:
        def spy = Spy(ClassUnderTest)

        then:
        spy.defaultPlusOne == 1

        when:
        spy.getDefault() >> 2

        then:
        spy.defaultPlusOne == 3

        when:
        spy.getDefaultPlusOne() >> 0

        then:
        spy.defaultPlusOne == 0 // fails on private
      }

Original issue reported on code.google.com by juraj.mi...@gmail.com on 15 Nov 2012 at 3:13

GoogleCodeExporter commented 8 years ago
Private methods are implicitly final. Hence there is no sane way to implement 
stubbing/mocking for them. You'll have to change visibility to protected or 
package-private.

Original comment by pnied...@gmail.com on 22 Nov 2012 at 6:22

GoogleCodeExporter commented 8 years ago
That said, it might be possible to make this work for classes written in 
Groovy. If you are interested in that, please open a new issue.

Original comment by pnied...@gmail.com on 22 Nov 2012 at 6:29