0

Test Class

Class TestClass{

    @Autowired
    AnyClass anyClass

    boolean testMethod() {
        boolean result = anyClass.method()
        if(result) {
            return !result
        }
        else {
            return !result
        }
    }
}

My Spock

class TestClassSpec implements Specification {

    AnyClass anyClass = Mock()
    TestClass testClass = new TestClass(anyClass: anyClass)

    def "check if opposite of result is returned"()  { 
        given: 
        anyClass.method >> {return true}

        when:
        boolean result = testClass.testMethod()

        then:
        result == false
    }
}

The result variable is always null when I try to debug. Is there anyway I can inject values into result variable without changing the original Test class?

Leonard Brünings
  • 12,408
  • 1
  • 46
  • 66
  • 1
    Please make sure to share an [MCVE](https://stackoverflow.com/help/mcve). The code you posted doesn't even fit together what is the relationship between `Test` and `TestClass` , how does `AnyClass` look like? And please use proper formatting, once you update your code. – Leonard Brünings Dec 24 '21 at 07:22
  • There was a typo in test. The definition of anyClass and methods don't matter. The question I have is how to inject values into 'result' variable in 'testMethod' – mino monster Dec 24 '21 at 08:22

2 Answers2

2

You code has several issues:

  1. You need to extend Specification not implement
  2. If you stub a method you need to include the (), e.g., anyClass.method >> {return true} would try to mock a property, the correct invocation is anyClass.method() >> true this is the main issue
  3. the { return true } is redundant if you just want to return a fixed value
  4. The if-else is entirely redundant
interface AnyClass {
    boolean method()
}

class TestClass{

    AnyClass anyClass

    boolean testMethod() {
        boolean result = anyClass.method()
        return !result        
    }
}

class TestClassSpec extends spock.lang.Specification {

    AnyClass anyClass = Mock()
    TestClass testClass = new TestClass(anyClass: anyClass)

    def "check if opposite of result is returned"()  { 
        given: 
        anyClass.method() >> true

        when:
        boolean result = testClass.testMethod()

        then:
        result == false
    }
}

Test it in the Groovy Console

Leonard Brünings
  • 12,408
  • 1
  • 46
  • 66
0

As noted in the comment, your code does not make fit well but I would suggest you inject the variable this way:

  def "check if opposite of result is returned"() {
    when:
    boolean result = testClass.testMethod()

    then:
    anyClass.method() >> false

    and:
    result == false
  }
Denis Kisina
  • 350
  • 4
  • 19