10

I am new to spock. I am trying to write a spock unit test against a standalone java app that uses JDK 1.7, Spring 3.1, Groovy 1.8.6, Spock 0.6, Maven 3.0.4. A basic hello world spock test is working. However when I try to test spring beans, I find that they are not getting injected. I use the approach mentioned here. businessObjectDao is null within when block. How do I get this working?

@ContextConfiguration(locations = "classpath*:test-appContext.xml")
class BusinessObjectPersistenceTest extends Specification {
    @Autowired
    BusinessObjectDao businessObjectDao

    def "business never set at least once"() {
        when:
            BusinessObjectDao.getBusinessObject()
        then:
            ...
    }
}
arrehman
  • 1,322
  • 6
  • 31
  • 42
  • Is `getBusinessObject` method actually _static_ (Capital `B` on `BusinessObjectDao` reference)? If so, then I don't think you'd need to inject an _instance_ of it in the first place? – cellepo Aug 31 '21 at 23:50
  • Probably a more recent Spring/Spock reference (for injection): https://spockframework.org/spock/docs/2.0/module_spring.html – cellepo Sep 01 '21 at 00:35

2 Answers2

21

you most likely forgot to include a Spock Spring dependency.

Here is how to get it using:

maven

<dependency>
   <groupId>org.spockframework</groupId>
   <artifactId>spock-spring</artifactId>
   <version>0.6-groovy-1.8</version>
</dependency>

gradle

'org.spockframework:spock-spring:0.6-groovy-1.8'

plain groovy

@Grapes(
    @Grab(group='org.spockframework', module='spock-spring', version='0.6-groovy-1.8')
)

*0.6-groovy-1.8 is the current version, if you need another one, just substitute

tolitius
  • 22,149
  • 6
  • 70
  • 81
  • The current version is 0.6-groovy-1.8. – Peter Niederwieser Mar 22 '12 at 22:00
  • yes, and it is [20 days old](http://repo1.maven.org/maven2/org/spockframework/spock-spring/0.6-groovy-1.8/). noted and corrected. – tolitius Mar 22 '12 at 22:16
  • I think this is a good answer, but let me just add one comment for `arrehman`. If this is a unit test and not an integration test what you are doing, You should be mocking that DAO. In any case +1 for the answer. – javing Dec 30 '12 at 23:21
  • @sfrj i think there is some disagreement in the testing world about your statement. it goes to mockists vs statists. some would say you should only mock adapters and ports. a dao is likely is neither. – Bill Turner Nov 20 '14 at 17:14
  • The **current** version can be found [here](https://mvnrepository.com/artifact/org.spockframework/spock-spring) – crusy May 19 '17 at 07:28
0

For others arriving here that don't have their test class annotated as a Bean (the example in this Question does have sufficient annotation for that), that would of course be at least a necessary prior step for injection (in general).

cellepo
  • 4,001
  • 2
  • 38
  • 57