【问题标题】:Grails unit testing help needed需要 Grails 单元测试帮助
【发布时间】:2010-12-05 07:19:05
【问题描述】:

我想测试一个调用服务的 Grails 控制器。我想嘲笑这项服务。该服务有一个方法:

JobIF JobServiceIF.getJob(int)

而 JobIF 有一个方法:

String JobIF.getTitle()

这是我的控制器

def 工作活动 = { JobIF 工作 = jobService.getJob(params.id) [职业:工作] }

我知道我需要模拟服务和作业类(两者都有具体的实现),但我很难理解 Groovy 模拟对象语法。如何模拟一项工作并将标题设置为某个内容,例如“架构师”,然后测试代码?

到目前为止我有:

无效的测试工作活动(){ def 控制器 = 新的 CareersController() ... // 嘲笑我不知道怎么做的东西 控制器.params.id = 12 def 模型 = controller.workActivities() assertEquals "建筑师",模型["职业"].getTitle() }

【问题讨论】:

    标签: unit-testing grails


    【解决方案1】:

    你基本上有两个选择

    1. 使用 Groovy 模拟类,即 MockForStubFor
    2. 通过调用GrailsUnitTestCasemockFor 方法来使用Grails 模拟类。该方法返回的类是GrailsMock的实例

    就个人而言,我发现 Groovy 模拟对象比 Grails 模拟更可靠。有时,我发现我的 Grails 模拟对象被绕过了,尽管我似乎正确设置了所有内容。

    这是一个如何使用 Groovy 模拟的示例:

    void testCreateSuccess() {
    
        def controller = new CareersController()
    
        // Create a mock for the JobService implementation class
        def mockJobServiceFactory = new MockFor(JobService)
    
        mockJobServiceFactory.demand.getJob {def id ->
            // Return the instance of JobIF that is used when the mock is invoked
            return new Job(title: "architect")
        }
    
        // Set the controller to use the mock service
        controller.jobService = mockJobServiceFactory.proxyInstance()
    
        // Do the test
        controller.params.id = 12
        def model = controller.workActivities()
        assertEquals "Architect", model["career"].getTitle()
    }
    

    使用Grails mocks的过程基本相同,只是调用了测试类的mockFor方法,而不是实例化MockFor

    【讨论】:

    • 谢谢。我可以再问一个问题吗?如果 JobService 有一个构造函数参数 - 我该如何指定?例如 JobService 将 JobDao 作为其构造函数参数。谢谢。
    • 顺便说一句,堆栈跟踪是:测试用例:testWorkActivities 耗时 0.344 秒导致错误无法从该列表中找到要调用的方法 ():public uk.co.cascaid.biz.job .JobObservableCachedService#(uk.co.cascaid.dao.job.JobDaoIF, uk.co.cascaid.biz.common.paging.PageCollectionServiceIF) public uk.co.cascaid.biz.job.JobObservableCachedService#( uk.co.cascaid.dao.job.JobDaoIF) org.codehaus.groovy.runtime.metaclass.MethodSelectionException:
    猜你喜欢
    • 2011-08-12
    • 2017-05-28
    • 1970-01-01
    • 2011-12-19
    • 1970-01-01
    • 1970-01-01
    • 2012-08-31
    • 1970-01-01
    • 2013-10-15
    相关资源
    最近更新 更多