Search code examples
javaspock

Swap number test case in spock


I am just trying to go through with Spock test framework and as per the documentation it looks better than JUnit and tried to write the simple test case but somehow it's not working.

Class:

public class SwapTwoNumber {
    public void swapNumber(int a,int b){
        a =a+b;
        b=a-b;
        a=a-b;

    }
}

Spock Test Groovy:

import spock.lang.Specification

class SwapTwoNumberTest extends Specification{
    def "swap to number as given. #a and #b"() {
     given:
      int a = 5
      int b = 6
     when:
      SwapTwoNumber sw =Mock()
      sw.swapNumber(a,b)
      then:
      a==6
      b==5

    }
}

Solution

  • I am not familiar with the testing framework you mentioned but this is most likely not a framework problem. You are passing primitives arguments.

    As stated in the docs

    Primitive arguments, such as an int or a double, are passed into methods by value. This means that any changes to the values of the parameters exist only within the scope of the method. When the method returns, the parameters are gone and any changes to them are lost.