How can I inject something into the session when unit testing a service
I have written a service that reads a CAS session variable ...
package cp
import edu.yale.its.tp.cas.client.filter.CASFilter
import javax.servlet.http.HttpSession
import org.springframework.web.context.request.RequestContextHolder
class AuthorizeService {
def username
def loginError
def permissions
def authCheck( String pageController, String pageAction ) {
username = getSession().getAttribute(CASFilter.CAS_FILTER_USER)
.....
Omitted the rest of this to save space.
.....
}
private HttpSession getSession() {
return RequestContextHolder.currentRequestAttributes().getSession()
}
I cannot figure out how to put something into the session in my test so that this piece of code will run.
Here's the test:
package cp
import grails.test.*
class AuthorizeServiceTests extends GroovyTestCase {
def AuthorizeService
protected void setUp() {
super.setUp()
}
protected void tearDown() {
super.tearDown()
}
void testAuthCheck() {
def isAuthorized
// No username in the session
isAuthorized = AuthorizeService.authCheck( 'welcome', 'index' )
assertEquals false, isAuthorized
// Mock the username to the rest of the 开发者_运维问答tests work
mockSession["CASFilter.CAS_FILTER_USER"] = "testUser"
.....
Omitted the rest of this to save space.
.....
}
When I run my test, here's the error I get back:
No such property: mockSession for class: cp.AuthorizeServiceTests groovy.lang.MissingPropertyException: No such property: mockSession for class: cp.AuthorizeServiceTests at cp.AuthorizeServiceTests.testAuthCheck(AuthorizeServiceTests.groovy:26)
I've been searching Google for 2 days now trying to find a way to inject something into mockSession or something similar so that I can test this service. I can see where it would be pretty easy to test this if this were a controller, but it appears that services are a whole different animal.
As a bit of background, I'm porting a working PHP application to Grails ... I'm a PHP guy, and this is my first forray into Grails, so I apologize if this is a noob question.
Grails 2.3.4:
import grails.util.GrailsWebUtil
class SomeTests extends GroovyTestCase {
void testSomething() {
def request = GrailsWebUtil.bindMockWebRequest()
def myDummyObject = new DummyObject()
request.session['myDummyObject'] = myDummyObject
// Run your code and make asserts
}
}
take a look at MockUtils
also try ControllerUnitTestCase
精彩评论