Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inject Services in Grails Unit Test

I know that you can simply inject a service in unit test method using:

defineBeans {
   someService(SomeService)
}

But when I need to inject service inside a service (the service someService calls itself another service some2Service). When I run the test with above code I receive:

Message: Cannot invoke method someMethod() on null object

Is it possible to inject a service into a service in the unit test?

Thanks. ;-)

like image 533
kuceram Avatar asked Sep 06 '12 14:09

kuceram


People also ask

What are unit tests in Grails?

Unit tests are typically run without the presence of physical resources that involve I/O such as databases, socket connections or files. This is to ensure they run as quick as possible since quick feedback is important. Since Grails 3.3, the Grails Testing Support Framework is used for all unit tests. This support provides a set of traits.

How does Grails make testing easier?

Hence, Grails provides many ways to making testing easier from low level unit testing to high level functional tests. This section details the different capabilities that Grails offers for testing. The first thing to be aware of is that all of the create-* and generate-\* commands create unit or integration tests automatically.

How do I Use dependency injection in Grails?

Grails supports "dependency injection by convention". In other words, you can use the property name representation of the class name of a service to automatically inject them into controllers, tag libraries, and so on. As an example, given a service called BookService, if you define a property called bookService in a controller as follows:

How to use Hibernate in Grails unit tests?

We are going to use a unit test for the dynamic finder with the help of HibernateSpec. It allows Hibernate to be used in Grails unit tests. It uses a H2 in-memory database. Test a limited set of domain classes, override getDomainClasses method and specify exactly which ones you wish to test.


1 Answers

To use spring beans in a unit test you need to do the following:

  • Include all the services and other beans the test depends on in the defineBeans closure.
  • Set the autowire property to true for beans that need to have other beans injected.

For example:

defineBeans {
    someService(SomeService) { bean ->
        bean.autowire = true
    }
    some2Service(Some2Service)
}
like image 137
ataylor Avatar answered Sep 16 '22 21:09

ataylor