cannot understand spock interaction - spock

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
}

Related

Grails Can't inject service to domain when test with Spock

When do grails unit test with Spock, can't auto inject a service instance to domain.
Below is my code.
Service:
class HiService {
public HiService(){
println "Init HiService," + this.toString()
}
def sayHi(String name){
println "Hi, ${name}"
}
}
Domain:
class User {
public User(){
if (hiService == null){
println "hiService is null when new User(${name})"
}
}
String name
def hiService
def sayHi(){
println "Before use hiService " + hiService?.toString()
hiService.sayHi(name)
println "End use hiService" + hiService?.toString()
}
}
TestCase:
#TestFor(HiService)
#Mock([User])
class HiServiceTest extends Specification {
def "test sayHi"() {
given:
def item = new User( name: "kitty").save(validate: false)
when: "Use service method"
item.sayHi()
then : "expect something happen"
assertEquals(1, 1)
}
}
The following was console log:
--Output from test sayHi--
Init HiService,test.HiService#530f5e8e
hiService is null when new User(null)
Before use hiService null
| Failure: test sayHi(test.HiServiceTest)
| java.lang.NullPointerException: Cannot invoke method sayHi() on null object
at test.User.sayHi(User.groovy:17)
at test.HiServiceTest.test sayHi(HiServiceTest.groovy:20)
The service initialized, but can't inject to domain. But when run app directly, service will auto-inject to domain
If you wan't autowiring it needs to be an integration test. If using Grails 3 then annotate with #Integration, if grails 2 then extend IntegrationSpec.
See: http://docs.grails.org/latest/guide/testing.html#integrationTesting
#Mock([User, HiService])
class HiServiceTest extends Specification {
def "test sayHi"() {
// ....
}
}
Since you are writing unit tests, your service will not be autowired. Also as you are unit testing the User class object, you should write the test in UserSpec (instead of UserServceTest; Suffixing Spec is the convention in Spock). Now you can mock the HiService instead like this:
class UserSpec extends Specification {
def "User is able to say hi"() {
given:
User user = new User(name: 'bla bla')
and: "Mock the user service"
def hiService = Mock(HiService)
user.hiService = hiService
when:
user.sayHi()
then:
1 * sayHiService.sayHi(user.name)
}
}

How to bind #Value annotated fields of service in unit tests?

Service:
#GrailsCompileStatic
class MyService {
final static String PLACEHOLDER = '<x>'
#Value('${myService.url}') // Suppose it http://example.com/doc-<x>.html
private String urlTemplate
String getSomeUrl(String lang) {
urlTemplate.replace(PLACEHOLDER, lang)
}
}
Unit test:
#TestFor(MyService)
class MyServiceSpec extends Specification {
#Unroll
void "test get some url for #lang"() {
when:
def someUrl = service.getSomeUrl(lang) // NullPointerException, because urlTemplate is null
then:
someUrl.endsWith(lang + '.html')
where:
lang << ['es', 'en']
}
}
So, as I mentioned above, urlTemplate is null (but config value exists in .properties). How to fix it?
Solution:
class MyServiceSpec extends IntegrationSpec {
MyService myService
#Unroll
void "test get some url for #lang"() {
when:
def someUrl = myService.getSomeUrl(lang)
then:
someUrl.endsWith(lang + '.html')
where:
lang << ['es', 'en']
}
}
Unit tests are used to test isolated units of code. If you are testing behavior that is dependent on the configuration value, inject it into the unit test to achieve reusable unit tests.
On the other hand, if you are testing that the variable is actually set or what the variable is set to, you need to use an integration test because you are basically testing your integration with Grails' configuration mechanism: http://docs.grails.org/latest/guide/testing.html#integrationTesting
As a third option, you could also use functional testing to verify that in the end everything appears to function as it is supposed to: http://docs.grails.org/latest/guide/testing.html#functionalTesting
How to bind #Value annotated fields of service in unit tests?
One way to do it...
#TestFor(MyService)
class MyServiceSpec extends Specification {
#Unroll
void "test get some url for #lang"() {
when:
service.urlTemplate = 'some value'
def someUrl = service.getSomeUrl(lang)
then:
someUrl.endsWith(lang + '.html')
where:
lang << ['es', 'en']
}
}
In case this helps someone.
I had an issue where a missing property variable used in a #Value was giving me an BeanExpressionException for a service unit test. I found that setting that variable in my application.yml for the test environment solved my problem in Grails 4.
#Value in question:
#Value("#{\${some_property_here}}") public Map<String, Map<String, Integer>> SOME_MAP_OF_MAPS

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
}

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 in Grails with groovy

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()
...
}
}

Resources