Manoj
Manoj

Reputation: 5612

Groovy test case with string array iteration

I have a test case where i need to test multiple strings and they are initialised as String[]

   myArray.each {
        shouldFail(IllegalArgumentException) {
            println "it = " + it
            testObj.testMyString("$prefix $it", mockBuilder);
         }
    }

the print statement shows that "it" is null. What am I doing wrong?

Upvotes: 2

Views: 648

Answers (3)

Gagan Agrawal
Gagan Agrawal

Reputation: 139

Each closure has its own "it". In your case when "it" was null, it was shouldFail closure's "it" and not myArray.each's closure.

Upvotes: 2

tim_yates
tim_yates

Reputation: 171184

If you name your each var, it should work:

myArray.each { element ->
    shouldFail(IllegalArgumentException) {
        println "it = $element"
        testObj.testMyString("$prefix $element", mockBuilder)
    }
}

Upvotes: 3

Manoj
Manoj

Reputation: 5612

it worked when I changed the code to this

 myArray.each {
        def testStr = it
        shouldFail(IllegalArgumentException) {
            println "it = " + testStr
            testObj.testMyString("$prefix $testStr", mockBuilder);
         }
    }

I guess "it" is not available in inner closures

Upvotes: 0

Related Questions