使用 spock 在要测试的函数中使用的模拟对象

Mock object used insided the to be tested function using spock

我可以通过多种方式模拟要测试的函数 class。但是如何模拟在待测方法中创建的对象呢? 我有这个要测试 class

 @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 传递到您的构造函数中,然后测试代码可以通过测试模拟。

但是,如果您想模拟代码内部的 class 构造,请在此处查看使用 GroovySpy 和 GroovyMock 模拟构造函数和 classes:http://spockframework.org/spock/docs/1.0/interaction_based_testing.html

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

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 是可配置的,然后您可以建立一个服务器 returns 一个已知字符串,并检查返回的字符串