vendredi 31 juillet 2015

Don't understand how interactions really work in Spock

Here's a super easy spock test case in Groovy.!! All classes/interface defined in this specification file. (A specification file in spock is simply a test case file).

Cannot seem to understand the workflow. How're mock objects being instantiated, injected, and destroyed in the test case workflow? Any help is appreciated...

Spock should be called 'Spooky', in my honest opinion ( :-) ), at least until one's very familiar with it..

import spock.lang.Specification

class WeatherServiceImpl {
    private URLAdapter urlAdapter;
    private URLConnection urlConn;

    public WeatherServiceImpl(urlAdapter){
        this.urlAdapter=urlAdapter
    }

    def run(city) {
        urlConn=urlAdapter.openConnection(city)
        return urlConn.getResponseCode()

    }

}

interface URLAdapter {
    def openConnection(city)

}


class WeatherServiceImplSpec extends Specification {

    def mockURLAdapter = Mock(URLAdapter)
    def mockURLConn    = Mock(HttpURLConnection)
    def weatherService=new WeatherServiceImpl(mockURLAdapter);


    def "Need to figure out the effects of lines: 'troublesome' and 'weirdo' "() {
        given:
        mockURLConn.getResponseCode()>> 9999
        mockURLAdapter.openConnection(_)>>mockURLConn;

        when:
        def result=weatherService.run("New York")

        then:
        // Uncommenting line 'troublesome' below throws a null-pointer exception:
        // java.lang.NullPointerException: Cannot invoke method getResponseCode() on null object
        //      at WeatherServiceImpl.run(URLAdapterConnectionSpec.groovy:29)
        //      at WeatherServiceImplSpec.delivers events to all subscribers(URLAdapterConnectionSpec.groovy:54)

        // Commenting out line 'troublesome' gives no issue!!

        // Line 'troublesome':
        // 1*mockURLAdapter.openConnection(_)

        // Line 'weirdo':
        // And yet, line 'weirdo' works just fine (i.e. test passes, no exception thrown)!!
        1*mockURLAdapter.openConnection(_)>>mockURLConn;

        //WTH is happening! ?
        result==9999


    }

}

Aucun commentaire:

Enregistrer un commentaire