gpt4 book ai didi

grails - 在对服务进行单元测试时,如何在 session 中注入(inject)一些东西

转载 作者:行者123 更新时间:2023-12-02 14:28:26 24 4
gpt4 key购买 nike

我编写了一个读取 CAS session 变量的服务......

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()
}

我无法弄清楚如何在我的测试中将某些东西放入 session 中,以便这段代码能够运行。

这是测试:
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.
.....

}

当我运行测试时,这是我得到的错误:

没有这样的属性:类的模拟 session :cp.AuthorizeServiceTests
groovy.lang.MissingPropertyException:没有这样的属性:类的模拟 session :cp.AuthorizeServiceTests
在 cp.AuthorizeServiceTests.testAuthCheck(AuthorizeServiceTests.groovy:26)


我已经在 Google 上搜索了 2 天,试图找到一种方法将一些东西注入(inject)到 mockSession 或类似的东西中,以便我可以测试这个服务。如果这是一个 Controller ,我可以看到在哪里测试它会很容易,但似乎服务是一个完全不同的动物。

作为背景知识,我正在将一个有效的 PHP 应用程序移植到 Grails ......我是一个 PHP 人,这是我第一次尝试 Grails,所以如果这是一个菜鸟问题,我深表歉意。

最佳答案

chalice 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
}
}

关于grails - 在对服务进行单元测试时,如何在 session 中注入(inject)一些东西,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4329035/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com