简体   繁体   中英

How to mock Shiro accessControl() method in grails unit test case

I am using shiro security in my grail application. Grails version : 2.2.1 shiro : 1.2.0

I have a problem in writing grails unit test case for the controller with filter enabled. When the test case run without filters then it is working fine, if it runs withFilters then it is failing for accessControl() method not found in the controller. I dont know how to make Shiro's api to be visible while running the test case.I referred shiro unit test case link http://shiro.apache.org/testing.html but I couldn't get any info regarding accessControl().I have given sample code how my classes and test case looks like

MyController.groovy

def create() { 
            // getting request parameters and validation 
            String emailId = params.emailId 
            def ret = myService.createUser(emailId) 

            return ret 
 }

MyControllerFilters.groovy

def filters = { 
                loginCheck(controller: 'user') { 
                    before = { 
                            //do some business checks 

                            // Access control by convention. 
                            accessControl() // This is a dynamic method injected by ShiroGrailsPlugin to FilterConfig, but this is not visible during the test case. 
                        } 
                } 

MyControllerTests.groovy

@TestFor(MyController) 
@Mock(MyControllerFilters) 
class MyControllerTests { 

        @Before 
        void setup() { 
            // initializing some variables 
        } 

        void testCreateUserWithFilter() { 

            request.accessAllowed = true 

            withFilters(action:"create") { 
                    controller.create() 
            } 

            assert response.message == "success" 
        } 
    }

Try to use:

ControllerOrService.metaClass.method = {
    return "" //what you need to be returned
}

Add parameters to closure if method take parameters:

 ControllerOrService.metaClass.method = { def a, def b ->
    return a + b
}

Don't forget to use full name of method when you mock them in that way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM