需要Grails单元测试帮助

Mat*_*att 3 grails unit-testing

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

JobIF JobServiceIF.getJob(int)

和JobIF有一个方法:

String JobIF.getTitle()

这是我的控制器

def workActivities = {
   JobIF job = jobService.getJob(params.id)
   [career:job]
}

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

到目前为止,我有:

void testWorkActivities() {
   def controller = new CareersController()
   ... // Mocking stuff I don't know how to do
   controller.params.id = 12
   def model = controller.workActivities()
   assertEquals "Architect", model["career"].getTitle()
}

Dón*_*nal 6

你基本上有两个选择

  1. 使用Groovy模拟类,即MockForStubFor
  2. 通过调用mockFor方法来使用Grails模拟类GrailsUnitTestCase.此方法返回的类是.的实例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()
}
Run Code Online (Sandbox Code Playgroud)

使用Grails模拟时,该过程基本相同,但您调用mockFor测试类的方法,而不是实例化MockFor.