Different ways of service injection in spock test cases

Posted By : Shiv Kumar | 17-Jun-2015

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

 

About Author

Author Image
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.

Request for Proposal

Name is required

Comment is required

Sending message..