Login user for Integration test when using Jsecurity plugin « Intelligrape Groovy & Grails Blogs

Login user for Integration test when using Jsecurity plugin

Posted by Amit Jain

Hello Friends,

I was using Jsecurity plugin in my project. There was an action in a controller which needed logged in user information and I was finding it difficult to write an integration test for the same. Then Brent Fisher shared the following code which worked nicely for both services and controllers:

import org.jsecurity.SecurityUtils
import com.aps.domain.security.JsecUser
import org.jsecurity.subject.Subject

class MyControllerTests extends GrailsUnitTestCase {	

  protected void setUp() {
	super.setUp()
	//following code sets admin as a logged in user
	def subject = [isAuthenticated: true,
		       principal: "admin"
		      ] as Subject

	SecurityUtils.metaClass.static.getSubject = {-> return subject }
	Subject.metaClass.getPrincipal = {-> return "admin" }
	...
  }
 ...
}	

Using metaclass, We changed the implementation of getPrincipal() and getSubject() to work in our way. So looking at this, I could see the power of a metaclass, which can be used to change or add new method implementations to an API which is not even accessible to us.

Cheers!

~~Amit Jain~~
amit@intelligrape.com
IntelliGrape Softwares

http://www.intellgrape.com

  • Share/Bookmark
This entry was posted on December 7th, 2009 at 3:16 pm and is filed under Grails . You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

One Response to “Login user for Integration test when using Jsecurity plugin”

  1. [...] we have to run code on bootstrap some of which requires a user to be logged in. I found a blog http://www.intelligrape.com/blog/?p=335 (thanks to Amit)regarding this topic but it was using metaprogramming to override the normal [...]

Leave a Reply