【问题标题】:grails code-coverage cannot acces to methodgrails代码覆盖无法访问方法
【发布时间】:2019-02-24 17:06:21
【问题描述】:

我正在尝试使用 Coverage 在 grails 2 中进行测试,但我无法访问方法:

它说: “java.lang.IllegalStateException:未找到线程绑定请求:您是指实际Web请求之外的请求属性,还是在原始接收线程之外处理请求?如果您实际上是在Web请求中操作并且仍然接收此消息,您的代码可能在 DispatcherServlet/DispatcherPortlet 之外运行:在这种情况下,请使用 RequestContextListener 或 RequestContextFilter 来公开当前请求..."

class UserController implements  ResourceLoaderAware{

def index(Integer max) {
    params.max = Math.min(max ?: 10, 100)
    respond User.list(params), model:[userInstanceCount: User.count()]
}

}

import grails.test.mixin.Mock
    import grails.test.mixin.TestMixin
    import grails.test.mixin.support.GrailsUnitTestMixin
    import spock.lang.Specification
    import com.snt.olucarodashboard.UserController
    import grails.test.mixin.TestFor


    @TestMixin(GrailsUnitTestMixin)

    class UserControllerSpec extends Specification {

        UserController controller=new UserController()
        void "Test the index action returns the correct model"() {
            when: "The index action is executed"
            controller.index(0)

        }
    }

有什么问题?

谢谢

【问题讨论】:

    标签: testing grails code-coverage


    【解决方案1】:

    不要自己实例化控制器,而是在类级别使用@TestFor注解

    import grails.test.mixin.TestFor
    
    @TestMixin(GrailsUnitTestMixin)
    @TestFor( UserController )
    class UserControllerSpec extends Specification {
    
        void "Test the index action returns the correct model"() {
            when: "The index action is executed"
                controller.index(0)
        }
    
    }
    

    【讨论】:

    • 非常感谢,现在它可以读取我的方法了!!但它说:“失败:| 测试索引操作返回正确的模型(UserControllerSpec)| java.lang.NullPointerException at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:130) at org.codehaus。 groovy.grails.orm.support.GrailsTransactionTemplate.execute(GrailsTransactionTemplate.groovy:85) 在 UserControllerSpec.Test 索引操作返回正确的模型” ...并且索引方法中的测试失败
    • 也许在UserController中使用“import org.springframework.transaction.annotation.Transactional”部分解决了问题,但随后出现错误:“java.lang.IllegalStateException: Method on class [com.snt .olucarodashboard.User] 在 Grails 应用程序之外使用。如果在使用模拟 API 或引导 Grails 的测试上下文中运行“如何使用 Mock 来解决它?谢谢
    猜你喜欢
    • 2013-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多