Different ways to inject service in unit test case :
In my current project, I have assigned the spock test case for the modules.I have faced the issues mostly in injection of dependencies.After some work around, some tips are here which makes the work easier. Some ways to inject service in tresr cases :
Way 1 : Mock using annotation
We can mock service using the @Mock annotation like :
@Mock([SomeService])
Way2 : If first way of mocking fails somehow then try the another way of mocking
def service = mockFor(SpringSecurityService)
def control = service.createMock()
(domain/controller/service).springSecurityService = control
Way 3 : If anyhow above defined methods of injection not work then inject the service using new object instance
(domain/controller/service).userService = new UserService()
Here are the ways to inject springsecurityService current user in unit test case :
For springSecurityService current user:
Way 1 : user should be available at this time
controller.springSecurityService = [currentUser:[id:user.id]]
Way 2 : user should be available at this time
controller.springSecurityService = [currentUser:user]
Way 3 :
def springSecurityService = [getCurrentUser: {-> return user }] as SpringSecurityService
service/controller.springSecurityService = springSecurityService
THANKS
More From Oodles
Ready to innovate? Let's get in touch
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Shiv Kumar
Shiv is an experienced Java Developer with a strong background in multiple technologies. He specializes in defining system architectures to ensure reliable and resilient solutions. He possesses a comprehensive understanding of the latest technologies and has hands-on experience in Core Java, Spring Boot, Hibernate, Apache Kafka messaging queue, Redis, as well as relational databases like MySQL and PostgreSQL, and non-relational databases like MongoDB. He excels in API implementations, Microservices, Web Services development, testing, and deployments. Shiv actively contributes to code enhancements and consistently delivers valuable contributions to various client projects, including Fabtrack, Pando, Pandojo, Digikam, WhatsApp Integration, Croniz, Punchin Application, Script TV, Bhaasha, and more. He demonstrates strong analytical skills and a creative mindset. In addition, he has a passion for reading books and exploring new technologies and innovations.