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. ;-)
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.
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.
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:
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.
To use spring beans in a unit test you need to do the following:
defineBeans
closure.autowire
property to true
for beans that need to have other beans injected.For example:
defineBeans {
someService(SomeService) { bean ->
bean.autowire = true
}
some2Service(Some2Service)
}
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