Reputation: 5381
I wrote an simple HTTP utility class, which takes a HTTP method name and a requesting URL then return the response.
In my Grails app, several Services will use this utility to get results of some Web API calls. However, I don't know how to unit test these Services. The utility is so simple that it only uses HttpURLConnection
to execute HTTP requests, no any other dependencies.
How should I unit test these Services? Should I make the utility as a property of the Services, so that this utility can be injected and mocked on them?
Any suggestions?
Upvotes: 0
Views: 288
Reputation: 4096
You can create a MockHttpUtility, and then use it for test environment.
You can modify resources.groovy so that for tests, the mockService will be injected in your services/controllers instead of real service.
switch(GrailsUtil.environment) {
case "test":
httpUtil(MockHttpUtil) {bean ->
bean.autowire = "byName"
}
}
This would work for integration tests.
For unit tests, you can define the mock service as below
void testFoo() {
defineBeans {
httpUtil(MockHttpUtil)
}
}
You can design mock http util such that it returns the expected response when called. Eg, you can have a constructor or a setter that will take the expected response, and when the utility method is called with http method and url, it will return the given response.
Upvotes: 1