Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spock rightShift (mocking) operator apparently not working

Here is my Spock unit test:

def "when favorite color is red then doSomething produces empty list of things"() {
    given:
    FizzBuzz fizzBuzz = Mock(FizzBuzz)
    fizzBuzz.name >> 'Dark Helmet'
    fizzBuzz.attributes >> [:]
    fizzBuzz.attributes["favcolor"] >> 'red'
    fizzBuzz.attributes["age"] >> '36'

    Something something = new Something(fizzBuzz)

    when:
    Whoah whoah = something.doSomething()

    then:
    !whoah.things
}

And here is the FizzBuzz mock:

public interface FizzBuzz extends Serializable {
    Map<String, Object> getAttributes();
}

When I run this I get:

java.lang.NullPointerException: Cannot invoke method rightShift() on null object

at com.commercehub.houston.SomethingSpec.when favorite color is red then doSomething produces empty list of things fail(SomethingSpec.groovy:18)

Process finished with exit code 255

The 'null object' its referring to on Line 18 is either fizzBuzz or its attributes map. Why?

like image 392
smeeb Avatar asked Jan 12 '16 12:01

smeeb


2 Answers

You're attempting to use multiple levels of indirection, and the >> is getting applied to the result of .attributes["favcolor"], which is null (since .attributes is an empty map). Instead, just initialize the map:

fizzBuzz.attributes >> [favcolor: 'red', age: 36]

(Also, did you really mean age to be a string?)

like image 98
chrylis -cautiouslyoptimistic- Avatar answered Nov 04 '22 07:11

chrylis -cautiouslyoptimistic-


In my case, I realized I was accidentally declaring the result of the when block.

when:
Whoah whoah = something.doSomething() >> expectedResult
like image 1
Forrest Avatar answered Nov 04 '22 08:11

Forrest