How to write a test case string for a method that calls other methods internally

Let's say I have a method that populates some data into a list and it internally calls another method (which I am testing myself) and populates some data into the list. Is there a better way to test?

How do I test an external method? Should I also validate the data from the inner method, otherwise it is ok to validate only the data populated by the outer method?

+3


source to share


1 answer


Given the following class:


class MyTestClass {
    int getAPlusB() { return getA() + getB() }
    int getA() { return 1 }
    int getB() { return 2 }
}

      



I can write the following test case to check that the arithmetic is correct, but also that getA()

and getB()

is actually called getAPlusB()

:



def "test using all methods"() { 
    given: MyTestClass thing = Spy(MyTestClass)
    when:  def answer = thing.getAPlusB()
    then:  1 * thing.getA()
           1 * thing.getB()
           answer == 3
}

      

So far, it runs all the code for all 3 methods - getA and getB are checked as callable, but the code in those methods is actually executed. In your case, you are testing the inner methods separately, and perhapse you don't want to call them at all during this test. Using spock spy, you can instantiate a real instance of the class under test, but with the ability to zero out certain methods you want to specify, the value returned is:

def "test which stubs getA and getB"() {
   given: MyTestClass thing = Spy(MyTestClass)
   when:  def answer = thing.getAPlusB()
   then:  1 * thing.getA() >> 5
          1 * thing.getB() >> 2
          answer == 7
}

      

+5


source







All Articles