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:
...
}
}
In Spring Boot, we can use Spring Framework to define our beans and their dependency injection. The @ComponentScan annotation is used to find beans and the corresponding injected with @Autowired annotation. If you followed the Spring Boot typical layout, no need to specify any arguments for @ComponentScan annotation.
In a Spring application, injecting one bean into another bean is very common. However, sometimes it's desirable to inject a bean into an ordinary object.
Spock has spring namespace support, so if you declare the spock namespace with xmlns:spock="http://www.spockframework.org/spring" you get access to the convenience functions for creating mocks.
As we can see, Spock has more readability and a clearer documented code, it does not need 3rd parties, and it is more powerful than JUnit. In the end, using Spock or JUnit or TestNG or anything else is absolutely up to you. They each have their pros and cons for sure.
you most likely forgot to include a Spock Spring dependency.
Here is how to get it using:
<dependency>
<groupId>org.spockframework</groupId>
<artifactId>spock-spring</artifactId>
<version>0.6-groovy-1.8</version>
</dependency>
'org.spockframework:spock-spring:0.6-groovy-1.8'
@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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With