【问题标题】:Mock private method in GrailsGrails 中的模拟私有方法
【发布时间】:2015-04-08 04:02:46
【问题描述】:

我是 grails 新手,在集成测试方面遇到困难。我有一个服务类,它在内部从私有方法调用外部服务。有什么方法可以模拟这个私有方法,这样我就可以避免集成测试的外部服务调用?请指导我。

示例代码如下:

import org.springframework.web.client.RestTemplate;

public class Service {
   final static RestTemplate REST = new RestTemplate()

   def get() {      
    def list = REST.getForObject(url, clazzObject, map) 
    list
}
}

集成测试类

class RackServiceIntegrationSpec extends IntegrationSpec {
     def service = new Service()

     void testApp(){
        setup:
        def testValues = ["name1", "name2"]
        service.metaClass.get = {String url, Class clazz, Map map -> testValues}

        when:
        def val = service.get()

        then:
        val.get(0) == 'name1'

    }
}

它实际上不是模拟 rest 调用,而是进行原始的 rest 调用并从数据库中获取值。我在这里做错了吗?

【问题讨论】:

  • 当您需要模拟私有方法时,它通常表示设计不佳。为什么你需要模拟这个方法?相反,应该模拟外部服务。
  • 私有方法具有进行外部服务调用的逻辑。我想绕过该服务并通过返回预定义的值来模拟它。
  • 这不是一个好的决定,嘲笑服务是更好的主意。
  • 谢谢@Opal。我这里更新了测试代码。

标签: grails integration-testing spock


【解决方案1】:

正如@Opal 已经评论的那样——你应该切断外部依赖,而不是模拟服务的内部细节(如私有方法)。但这当然只适用于单元测试类型的测试。根据您的测试目标,您可以切断外部内容或进行实际调用并在另一侧使用模拟(两者都是不同级别的两个有效测试)。

当您想在进行电汇之前进行模拟时,您应该使用 RestTemplate 的模拟实例来进行(这意味着您必须让它可注入 - 无论如何这是一个好主意,因为它是一个外部依赖项)。但是spring提供了一个更好的解决方案:MockRestServiceServer

class RackServiceIntegrationSpec extends IntegrationSpec {
 def service = new Service()
   def 'service calls the external http resource correct and returns the value'() {
    setup: 'create expectations on the http interactions'
    MockRestServiceServer mockServer  = MockRestServiceServer.createServer(service.REST)
    mockServer.expect(requestTo("/customers/123")).andRespond(withSuccess("Hello world", MediaType.TEXT_PLAIN));

    when: 'service gets called'
    def val = service.get()

    then: 'http interactions were successful given the assertions above'
    mockServer.verify();

    and: 'your other assertions'
    val.get(0) == 'name1'

  }
}

欲了解更多信息,请参阅spring testing documentation

【讨论】:

  • 谢谢@Mario David,我会检查一下。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-03-15
  • 1970-01-01
  • 1970-01-01
  • 2018-05-03
  • 2016-05-22
  • 2018-07-17
  • 1970-01-01
相关资源
最近更新 更多