Search code examples
grailstestingspock

How to test class with @Autowired using Spock


I have a class in src/groovy like this

public class MyClass {

@AutoWired
SomeOtherClass someOtherClass

String test() {
    return someOtherClass.testMethod()
}
}

When I write a test for this method I am getting an error: Cannot invoke method testMethod() on null object.

This is my test :-

def "test test" () {
    expect:
        myClass.test() == "somevalue"
}

What am I doing wrong? Is there a way to mock the @Autowired class?


Solution

  • You need to mock your someOtherClass. Something like this

    def "test test"(){
        setup:
        myClass.someOtherClass = Mock(SomeOtherClass)
        myClass.someOtherClass.testMethod() >> "somevalue"
    
        expect:
        myClass.test() == "somevalue"
    }