Unit testing 使用spock在待测函数中使用的模拟对象

Unit testing 使用spock在待测函数中使用的模拟对象,unit-testing,groovy,mocking,spock,Unit Testing,Groovy,Mocking,Spock,我可以用几种方式模拟待测试类的函数。但是如何模拟在待测试方法中创建的对象呢? 我要在课堂上测试这个 @Grab('org.codehaus.groovy.modules.http-builder:http-builder:0.7') import groovyx.net.http.HTTPBuilder class totest { def get() { def http = new HTTPBuilder('http://www.google.com')

我可以用几种方式模拟待测试类的函数。但是如何模拟在待测试方法中创建的对象呢? 我要在课堂上测试这个

 @Grab('org.codehaus.groovy.modules.http-builder:http-builder:0.7')
 import groovyx.net.http.HTTPBuilder
 class totest {
     def get() {
         def http = new HTTPBuilder('http://www.google.com')
         def html = http.get( path : '/search', query : [q:'Groovy'] )
         return html
     }   
 }     
如何模拟http.get以便测试get函数:

class TestTest extends Specification {
     def "dummy test"() {
         given:
             // mock httpbuilder.get to return "hello"
             def to_test = new totest()
         expect:                                                                                               
             to_test.get() == "hello"
     }   
 }

更好的方法是将HTTPBuilder传递到构造函数中,然后测试代码可以通过测试模拟

但是,如果您想模拟代码内部正在进行的类构造,请在此处查看使用GroovySpy和GroovyMock模拟构造函数和类:

您需要执行以下类似代码的操作:

import spock.lang.Specification

import groovyx.net.http.HTTPBuilder

class totest {
    def get() {
        def http = new HTTPBuilder('http://www.google.com')
        def html = http.get( path : '/search', query : [q:'Groovy'] )
        return html
    }
}

class TestTest extends Specification{

    def "dummy test"() {

        given:'A mock for HTTP Builder'
        def mockHTTBuilder = Mock(HTTPBuilder)

        and:'Spy on the constructor and return the mock object every time'
        GroovySpy(HTTPBuilder, global: true)
        new HTTPBuilder(_) >> mockHTTBuilder

        and:'Create object under test'
        def to_test = new totest()

        when:'The object is used to get the HTTP result'
        def result = to_test.get()

        then:'The get method is called once on HTTP Builder'
        1 * mockHTTBuilder.get(_) >> { "hello"}

        then:'The object under test returns the expected value'
        result == 'hello'
    }
}

你在这里测试什么?你关心这个方法是如何得到结果的吗?你肯定更关心它是否能得到正确的结果?在这种情况下,应该更改方法以使URL可配置,然后您可以建立一个返回已知字符串的服务器,并检查是否将字符串返回给OP:是的,实际上,全局Groovy模拟是在这里工作的技术技巧,但是(1)它只适用于Groovy代码,而不适用于Java,而且最重要的是-(2)每当您需要Groovy模拟时,尤其是全局模拟,或者需要用于静态方法的PowerMock等工具时,所有的警报都会响起。糟糕的应用程序设计是重构以实现更好的解耦(依赖项注入,而不是隐藏在方法体中的类自己创建依赖项)和更好的可测试性的原因。这绝不是升级“测试武器库”以避免重构的理由。