模拟对象使用spock确定要测试的功能

时间:2018-03-04 10:50:59

标签: 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')
         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"
     }   
 }

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分: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'
    }
}