使用spock在被测试函数内部使用的模拟对象

问题描述 投票:0回答:2

我可以用几种方式模拟一个被测试类的功能。但是如何模拟在被测试方法中创建的对象?我有这个要测试的课

 @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"
     }   
 }
unit-testing groovy mocking spock
2个回答
0
投票

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

但是如果你想模拟代码内部的类构造,那么在这里看看使用GroovySpy和GroovyMock的模拟构造函数和类: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'
    }
}

1
投票

你在这里测试什么?你关心方法得到它的结果吗?当然,你更关心它能得到正确的结果吗?在这种情况下,应该更改方法以使URL可配置,然后您可以站起来返回已知字符串的服务器,并检查该字符串是否已返回

© www.soinside.com 2019 - 2024. All rights reserved.