How to call Service in Grails with groovy - grails

I have one service in that i have a method to call and how can i acces this service.
I have seen sms plugin and installed it and How can i send sms from my application to the different mobiles.I followed the grails sms plugin but i didn't get any results ecxept ecxeptions
class SipgateService {
static transactional = true
def serviceMethod() {
def sipgateService
//def phoneNumber = 'XXXXXXXXXX' //phoneNumber according to E.164 specification
//working alternative:
println "service"
def phoneNumber = 'XXXXXXXXXX'
def result = sipgateService.sendSMS(phoneNumber, 'This is my Text to send!')
result ? 'Sending Successful':'Sending failed'
println "after service"
}
}
Please explain me with an example.
thanks alot in advance.

If you want to call the plugin from a service method, you would need to do:
change the name of your service (so it isn't called SipgateService)
Add the def sipgateService as a class definition, not a method one
Does this work?
class MySMSService {
static transactional = true
def sipgateService // This will be injected from the SMS plugin
def serviceMethod() {
println "service"
def phoneNumber = 'XXXXXXXXXX'
def result = sipgateService.sendSMS(phoneNumber, 'This is my Text to send!')
result ? 'Sending Successful':'Sending failed'
println "after service"
}
}
Then, from a controller, define the link to MySMSService at class level, and call your serviceMethod method ie:
class MyController {
def mySMSService // this will be injected from your service
// then, when you want to use it (from an action)
def someAction = {
...
mySMSService.serviceMethod()
...
}
}

Related

Jenkins spock: Mocking http-request-plugin's httpRequest

Somewhere in my shared library I got a helper class like this:
class Helper {
def script
Helper(script) {
this.script = script
}
void sendTemplate(String webhook, String template, Map<String, String> values, TemplateMapper mapper) {
def body = mapper.map(template, values)
def resp = script.httpRequest(contentType: 'APPLICATION_JSON', httpMode: 'POST',
requestBody: body, url: webhook)
if (resp.status != 200) {
throw new UnableToNotifyException()
}
}
}
I'm trying to test said class like so:
class HelperSpec extends JenkinsPipelineSpecification {
def helper
def setup() {
helper = new Helper(this)
}
def "a test"() {
setup:
def webhook = 'aWebhook'
def template = '%replaceMe'
def values = ['%replaceMe': 'hello world!']
def mapper = new SimpleTemplateMapper()
getPipelineMock('httpRequest')(_) >> [status: 200]
when:
helper.sendTemplate(webhook, template, values, mapper)
then:
1 * getPipelineMock('httpRequest')(_)
}
}
I'm using gradle and my build.gradle file has
testImplementation 'org.jenkins-ci.plugins:http_request:1.10#jar'
Other steps' tests run perfectly but with this one I always get
java.lang.IllegalStateException: There is no pipeline step mock for [httpRequest].
1. Is the name correct?
2. Does the pipeline step have a descriptor with that name?
3. Does that step come from a plugin? If so, is that plugin listed as a dependency in your pom.xml?
4. If not, you may need to call explicitlyMockPipelineStep('httpRequest') in your test's setup: block.
And when I use explicitlyMockPipelineStep('httpRequest') I get a null pointer exception, because, I presume, the default mock returns a null.
Is there anything I'm missing in the test to get it working? Thanks in advance!!!

Mocking methods in grails integration test carries over to other tests

I have an integration test where I sometimes want to mock the return of a service method. However, I have seen that once I mock that method, the subsequent tests that call it will also use the mocked function.
Is this normal? If so, how can I have test which sometimes use mocked functions and sometimes use the real implementation?
Here is my code:
MyController {
def someService
def save(){
...
def val = someService.methodToMock()//sometimes want to mock other times, not
...
}
}
MyTest {
def "test 1"(){
...
//I want to mock here
myController.someService.metaClass.methodToMock = { [] }
...
myController.save()
}
def "test 2"(){
...
//I don't want to mock here, however
// it is returning the mocked results
myController.save()
}
}
In general you don't want to change anything to do with metaclasses in integration or functional tests, only in unit tests. It's expected that you'll be doing this in unit tests and there's automatic support for restoring the original metaclass after each test or after each test class runs depending on the version of Grails and how things are configured. But this isn't the case in integration tests.
There are several different approaches you can use. If you use untyped dependency injection, e.g. def someService, then you can overwrite the real service instance with anything you want, and as long as it has the method(s) that you'll be invoking during the test method the controller won't know or care that it's not the real service.
I like to use a map of closures in this case, since Groovy will invoke a closure as if it were a method. So for 'test 1' you could do this:
def "test 1"() {
...
def mockedService = [methodToMock: { args -> return ... }]
myController.someService = mockedService
...
myController.save()
}
This works because you get a new instance of the controller for each test, and you change the service just for that instance, but the real service isn't affected at all.
Your controller invokes someService.methodToMock(), which is actually someService.get('methodToMock').call(), but the map access and closure invocation syntax can take advantage of Groovy's syntactic sugar to look like a regular method call.
Another option is to subclass the service and override the method(s) that you want, and replace the injected instance with that. This or something like it would be necessary if you type the dependency injection (e.g. SomeService someService). Either create a named subclass (class TestSomeService extends SomeService { ... }) or create an anonymous inner class:
def "test 1"() {
...
def mockedService = new SomeService() {
def methodToMock(args) {
return ...
}
}
myController.someService = mockedService
...
myController.save()
}
Altering the metaClass in one test will absolutely affect other tests. You're altering the groovy system, and need to perform some special cleanup if you're metaClassing. At the end my methods where I metaClass, I call a function to revoke the metaClass changes, passing in the name of the class that was metaClassed, and the instance metaClassed if there was one.
def "some authenticated method test"() {
given:
def user = new UserDomain(blah blah blah)
controller.metaClass.getAuthenticatedUser = { return user }
when:
controller.authenticatedMethod() // which references the authenticated user
then:
// validate the results
cleanup:
revokeMetaClassChanges(theControllerClass, controller)
}
private def revokeMetaClassChanges(def type, def instance = null) {
GroovySystem.metaClassRegistry.removeMetaClass(type)
if (instance != null) {
instance.metaClass = null
}
}
Alternatively, you can just mock the service in the test. A method similar to that mentioned by Burt could be:
def "some test"() {
given:
def mockSomeService = mockFor(SomeService)
mockSomeService.demand.methodToMock(1) { def args ->
return []
}
controller.someService = mockSomeService.createMock()
when:
controller.save()
then:
// implement your validations/assertions
}

cannot understand spock interaction

Here's a unit test that works fine.
#Subject([WeatherServiceImpl.class,URLConnection.class])
class WeatherServiceImplSpec extends Specification{
def "First spock test I ever wrote"(){
given: "some mock objects"
//1. define mock HttpURLConnection object
def mockConnObj=Mock(HttpURLConnection.class)
//2. defn of another mock
def mockURLAdaptor=Mock(URLAdapter)
when: "define some calls"
def test=new WeatherServiceImpl(mockURLAdaptor)
test.run("Raleigh")
then: "make some assertions"
1*mockURLAdaptor.openConnection(_)>>mockConnObj
1*mockConnObj.getResponseCode()
}//end def test
}
What I don't understand is that if I do this in the 'given' block:
def mockURLAdaptor = Mock(URLAdapter) >> {
​ openConnection(_) >> mockConnObj
}
then the method stub doesn't actually return the mock connection object as intended. To me, this is the more natural flow of expressions. Doing the same thing in the 'then' block, however, works as intended. Not sure what's going on here. Can't seem to find a relevant discussion on the web. I may also post this on stackoverflow.
Here's the class under test:
package com.icidigital.services.impl
import com.icidigital.Helpers.URLAdapter
import com.icidigital.services.IWeatherService
public class WeatherServiceImpl implements IWeatherService {
private URLAdapter urlAdapter;
private URLConnection urlConn;
public WeatherServiceImpl(URLAdapter urlAdapter){
//injecting this dependency, so I can unit test
//by injecting a mock URLAdapter instance. In
//normal operation, urlAdaptee would be an instance
//of URLWrapper, which simply wraps around the
// URL class, which is a final class and cannot
// be mocked normally.
this.urlAdapter=urlAdapter;
}
public String run(String city){
...
..
urlConn=urlAdapter.openConnection(city);
//(throws a null pointer exception while spock-ing)
urlConn.setRequestMethod("GET");
}
}
And here's the url adapter that exposes the method: openConnection. In the running code, there is a class URLWrapper that simply wraps around the java.net.URL class. I needed to do this to get around the fact that I couldn't directly mock the java.net.URL class since it is a final class.
interface URLAdapter {
public HttpURLConnection openConnection(String cityName);
}
If you want to return some object you should use a Stub instead.
#Subject([WeatherServiceImpl.class,URLConnection.class])
class WeatherServiceImplSpec extends Specification{
def "First spock test I ever wrote"(){
given: "some mock objects"
//1. define mock HttpURLConnection object
def mockConnObj=Mock(HttpURLConnection.class)
//2. defn of another mock
def mockURLAdaptor=Stub(URLAdapter)
mockURLAdaptor.openConnection(_)>>mockConnObj
when: "define some calls"
def test=new WeatherServiceImpl(mockURLAdaptor)
test.run("Raleigh")
then: "make some assertions"
1*mockConnObj.getResponseCode()
}//end def test
}
You can do it with Mocks as well, I just tried this and it worked
def "First spock test I ever wrote"() {
given: "some mock objects"
//1. define mock HttpURLConnection object
def mockConnObj = Mock(HttpURLConnection.class)
//2. defn of another mock
def mockURLAdaptor = Mock(URLAdapter)
1 * mockURLAdaptor.openConnection(_) >> mockConnObj
when: "define some calls"
def test = new WeatherServiceImpl(mockURLAdaptor)
test.run("Raleigh")
then: "make some assertions"
1 * mockConnObj.getResponseCode()
}//end def test
Hope it helps!
The following work(s):
#Subject([WeatherServiceImpl.class,URLConnection.class])
class WeatherServiceImplSpec extends Specification{
def "First spock test I ever wrote"(){
given: "some mock objects"
//1. define mock HttpURLConnection object
def mockConnObj=Mock(HttpURLConnection.class)
//=========================================
//2. defn of another mock
// Either/Or:
//def mockURLAdaptor=Mock(URLAdapter)
def mockURLAdaptor=Stub(URLAdapter)
//followed by:
mockURLAdaptor.openConnection(_)>>mockConnObj
//OR
def mockURLAdaptor=Stub(URLAdapter){
openConnection(_)>>mockConn
}
//BUT NOT:
def mockURLAdaptor=Mock(URLAdapter){
openConnection(_)>>mockConn
}
//=========================================
when: "define some calls"
def test=new WeatherServiceImpl(mockURLAdaptor)
test.run("Raleigh")
then: "make some assertions"
1*mockConnObj.getResponseCode()
}//end def test
}

Groovy MetaClass change to Service Under Test is not used by Spock

Within a Spock unit test, I am trying to test the behaviour of a method findRepositoriesByUsername independent of getGithubUrlForPath, both belonging to the same service.
Repeated attempts to use the metaClass have failed:
String.metaClass.blarg produces an error No such property: blarg for class: java.lang.String
service.metaClass.getGithubUrlForPath to modify the service instance doesn't work
GithubService.metaClass.getGithubUrlForPath to modify the service class doesn't work
Tried adding/modifying methods on the metaClass in the test methods' setup and when blocks, neither worked as expected
The test:
package grails.woot
import grails.test.mixin.TestFor
#TestFor(GithubService)
class GithubServiceSpec extends spock.lang.Specification {
def 'metaClass test'() {
when:
String.metaClass.blarg = { ->
'brainf***'
}
then:
'some string'.blarg == 'brainf***'
}
def 'can find repositories for the given username'() {
given:
def username = 'username'
def requestPathParts
when: 'the service is called to retrieve JSON'
service.metaClass.getGithubUrlForPath = { pathParts ->
requestPathParts = pathParts
}
service.findRepositoriesByUsername(username)
then: 'the correct path parts are used'
requestPathParts == ['users', username, 'repos']
}
}
The service:
package grails.woot
import grails.converters.JSON
class GithubService {
def apiHost = 'https://api.github.com/'
def findRepositoriesByUsername(username) {
try{
JSON.parse(getGithubUrlForPath('users', username, 'repos').text)
} catch (FileNotFoundException ex) {
// user not found
}
}
def getGithubUrlForPath(String ... pathParts) {
"${apiHost}${pathParts.join('/')}".toURL()
}
}
I've tested the String.metaClass.blarg example in the groovy shell (launched by grails), and it did as expected.
Do I have a fundamental misunderstanding here? What am I doing wrong? Is there a better way to handle the desired test (replacing a method on the service under test)?
This is how the tests can be written to make them pass:
def 'metaClass test'() {
given:
String.metaClass.blarg = { -> 'brainf***' }
expect:
// note blarg is a method on String metaClass
// not a field, invoke the method
'some string'.blarg() == 'brainf***'
}
def 'can find repositories for the given username'() {
given:
def username = 'username'
def requestPathParts
when: 'the service is called to retrieve JSON'
service.metaClass.getGithubUrlForPath = { String... pathParts ->
requestPathParts = pathParts
[text: 'blah'] // mimicing URL class
}
service.findRepositoriesByUsername(username)
then: 'the correct path parts are used'
requestPathParts == ['users', username, 'repos']
}
Why don't you use Spock's great Mocking abilities?
Look at http://spockframework.github.io/spock/docs/1.0/interaction_based_testing.html#_creating_mock_objects
There is no need to peek inside metaclass itself, you can create some stub object, and demanded method will be called instead of original one. Also you can use Groovy's MockFor and StubFor, they can be a little bit easier.
You cannot fully trust metaclass inside spock tests specification.
There is some complex logic inside it, which can easyly mess thing's up. Try run some tests under debugger, and you will see it.
Spock uses metaclasses under the hood. It can override your own try's.

how to call service from controller in grails

I have a service class and i am trying to call the method of the service in my controller as below.
class LogListController {
def ListLogDetails = {
println "We are inside List log Details-->"+params
def logListHelperService
logListHelperService.getFilePath(params)
}}
Exception Message: Cannot invoke method getFilePath() on null object
what is my mistake there..
def logListHelperService
must be declared outside of the ListLogDetails definition
def logListHelperService
def ListLogDetails = {
println "We are inside List log Details-->"+params
logListHelperService.getFilePath(params)
}
should work

Resources