user3450486
user3450486

Reputation: 235

Groovy easy way to mock HTTP request

I have very simple connector to connect to rest API:

class ApiConnector {
   def url

   ApiConnector(url) {
      this.url = url
  }

  def get(enpointName) {
    "$url/$endpointName".toUrl().text
  }
}

And my problem is that I want to have unit tests for the get method with some mocked outputs. I want to do this with Spock but don't know how actually can I approach this. Any help?

Upvotes: 0

Views: 2621

Answers (2)

SebaJack
SebaJack

Reputation: 151

You can mock this method in test manually. Examle:

ApiConnector.metaClass.get = {endpoint -> "Return some mock data for this ${endpoint}"}

And if you call method get you receive the mocked value. In other way you can use some mock lib.

Upvotes: 0

injecteer
injecteer

Reputation: 20699

What's wrong with plain meta-programming?

URL.class.metaClass.getText = { 'test text' }

'test text' == "http://stackoverflow.com".toURL().text

Upvotes: 2

Related Questions