【问题标题】:How can I inject something into the session when unit testing a service在对服务进行单元测试时,如何在会话中注入一些东西
【发布时间】:2010-12-01 20:54:37
【问题描述】:

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

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

我不知道如何在我的测试中将一些东西放入会话中,以便这段代码能够运行。

这是测试:

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

     }

当我运行测试时,我得到的错误如下:

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

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

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

【问题讨论】:

  • mockSessionMvcUnitTestCase 类的属性,而不是GroovyTestCase 的属性。

标签: grails


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    看看MockUtils

    也可以试试 ControllerUnitTestCase

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-22
    • 2020-07-10
    • 1970-01-01
    相关资源
    最近更新 更多