首页 > 解决方案 > grails restful groovy 无法解析符号

问题描述

我正在尝试通过以下链接学习 grails:https : //guides.grails.org/rest-hibernate/guide/index.html 并根据页面指南创建控制器 ProductController 后,我收到以下错误:

Unable to resolve class ProductService in ProductController

我是 groovy 的新手,并试图通过导入必要的包来解析类引用,但链接没有显示任何导入来解析此类。ProductController.groovy 中没有 ProductService productService 的显式导入语句。以下是这些类: ProductController:

package hibernate.example

import groovy.transform.CompileStatic
import grails.rest.*
import grails.converters.*

@CompileStatic
class ProductController extends RestfulController {
    static responseFormats = ['json', 'xml']
    ProductController() {
        super(Product)
    }
    ProductService productService

def search(String q, Integer max ) { 
    if (q) {
        respond productService.findByNameLike("%${q}%".toString(), [max: Math.min( max ?: 10, 100)]) 
    }
    else {
        respond([]) 
    }
}
}

产品控制器规格:

package hibernate.example

import org.grails.testing.GrailsUnitTest
import spock.lang.Specification

@SuppressWarnings('MethodName')
class ProductControllerSpec extends HibernateSpec implements ControllerUnitTest<ProductController> {

    def setup() {
    }

    def cleanup() {
    }

    static doWithSpring = {
    jsonSmartViewResolver(JsonViewResolver)
    }

    void 'test the search action finds results'() {
        given:
        controller.productService = Stub(ProductService) {
            findByNameLike(_, _) >> [new Product(name: 'Apple', price: 2.0)]
        }
        when: 'A query is executed that finds results'
        controller.search('pp', 10)

        then: 'The response is correct'
        response.json.size() == 1
        response.json[0].name == 'Apple'
    }
}

标签: grailsgroovy

解决方案


推荐阅读