0

I modified the code from here to look very much like the code I have and am trying to create Unit Tests for. While I would like to ask "what is the best way" to test this, I will be quite satisfied with any way to create a decent Unit Test! I looked at Spock, GroovyTestCase and GMock, while each of them may be quite capable of creating such a test I found the documentation for such an example lacking in all cases.

class Searcher {

    def http = new HTTPBuilder('http://ajax.googleapis.com')

    def _executeSearch = { searchQ -> {
            req ->
            uri.path = '/ajax/services/search/web'
            uri.query = searchQ
            requestContentType = URLENC
            response.success = { resp, reader ->
                assert resp.statusLine.statusCode == 200
                reader.text
            }
            response.failure = { resp -> println "FAILURE! ${resp.properties}" 
                                 resp.statusLine.statusCode  }
        }
    }

    def executeSearch(query) {
        // http.setHeaders(Accept: 'application/json')  // I want JSON back, but this not important
        http.request(GET, _executeGetCommand(query))
    }
}

What I want/need to do is to mock 'http' in such a way that I can test:

1. uri.query is getting properly set via the passed in data
2. calls to response.success return mocked test data
3. calls to failure get executed and return the failure code

I am probably approaching this entirely incorrectly and will be open to the "right way" of going about unit testing such code. Please bear with me though as this is new to me!

JoeG
  • 7,191
  • 10
  • 60
  • 105
  • Deciding to use `spock` is a wise decision. What have you tried yet in spock? – dmahapatro Nov 05 '13 at 02:46
  • Funny, I thought you would have said that was a "very logical" decision - haha. Haven't tried anything as every example I found was for basically trivial stuff and could not find a sample Specification for anything remotely like the above. – JoeG Nov 05 '13 at 11:37

1 Answers1

0

I would use Spock mock's for your test case. They should be quite straightforward, since you don't need any actual network interaction during unit testing.

Spock mocks are documented pretty well in the new spock docs

If you do want to test web services from the client side, check out geb, which works well as a companion to spock. Geb is documented in the Book of Geb Integration testing over the web obviously involves more moving parts, so you're right to start by mocking out the server side.

Alex Blakemore
  • 11,301
  • 2
  • 26
  • 49