Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inject spring beans into spock test

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:
            ...
    }
}
like image 975
arrehman Avatar asked Mar 21 '12 19:03

arrehman


People also ask

How do you inject beans in the spring?

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.

Can you inject beans?

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.

What is Spock spring?

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.

Is Spock better than JUnit?

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.


Video Answer


1 Answers

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

like image 95
tolitius Avatar answered Oct 09 '22 11:10

tolitius