Thought static method can’t be easy to mock, stub nor track? Wrong!

No matter why, no matter is it a good idea. Sometimes one just wants to check or it’s necessary to be done. Mock a static method, woot? Impossibru! In pure Java world it is still a struggle. But Groovy allows you to do that really simple. Well, not groovy alone, but with a great support of Spock. Lets move on straight to the example. To catch some context we have an abstract for the example needs. A marketing project with a set of offers. One to many. import spock.lang.Specification class OfferFacadeSpec extends Specification { OfferFacade facade = new OfferFacade() def setup() { GroovyMock(Project, global: true) } def 'delegates an add offer call to the domain with proper params'() { given: Map params = [projId: projectId, name: offerName] when: Offer returnedOffer = facade.add(params) then: 1 * Project.addOffer(projectId, _) >> { projId, offer -> offer } returnedOffer.name == params.name where: projectId | offerName 1 | 'an Offer' 15 | 'whasup!?' 123 | 'doskonała oferta - kup teraz!' } } So we test a facade responsible for handling “add offer to the project” call triggered  somewhere in a GUI. We want to ensure that static method Project.addOffer(long, Offer) will receive correct params when java.util.Map with user form input comes to the facade.add(params). This is unit test, so how Project.addOffer() works is out of scope. Thus we want to stub it. The most important is a GroovyMock(Project, global: true) statement. What it does is modifing Project class to behave like a Spock’s mock. GroovyMock() itself is a method inherited from Specification.  The global flag is necessary to enable mocking static methods. However when one comes to the need of mocking static method, author of Spock Framework advice to consider redesigning of implementation. It’s not a bad advice, I must say. Another important thing are assertions at then: block. First one checks an interaction, if the Project.addOffer() method was called exactly once, with a 1st argument equal to the projectId and some other param (we don’t have an object instance yet to assert anything about it). Right shit operator leads us to the stub which replaces original method implementation by such statement. As a good stub it does nothing. The original method definition has return type Offer. The stub needs to do the same. So an offer passed as the 2nd argument is just returned. Thanks to this we can assert about name property if it’s equal with the value from params. If no return was designed the name could be checked inside the stub Closure, prefixed with an assert keyword. Worth of  mentioning is that if you want to track interactions of original static method implementation without replacing it, then you should try using GroovySpy instead of GroovyMock. Unfortunately static methods declared at Java object can’t be treated in such ways. Though regular mocks and whole goodness of Spock can be used to test pure Java code, which is awesome anyway :)No matter why, no matter is it a good idea. Sometimes one just wants to check or it’s necessary to be done. Mock a static method, woot? Impossibru! In pure Java world it is still a struggle. But Groovy allows you to do that really simple. Well, not groovy alone, but with a great support of Spock. Lets move on straight to the example. To catch some context we have an abstract for the example needs. A marketing project with a set of offers. One to many. import spock.lang.Specification class OfferFacadeSpec extends Specification { OfferFacade facade = new OfferFacade() def setup() { GroovyMock(Project, global: true) } def 'delegates an add offer call to the domain with proper params'() { given: Map params = [projId: projectId, name: offerName] when: Offer returnedOffer = facade.add(params) then: 1 * Project.addOffer(projectId, _) >> { projId, offer -> offer } returnedOffer.name == params.name where: projectId | offerName 1 | 'an Offer' 15 | 'whasup!?' 123 | 'doskonała oferta - kup teraz!' } } So we test a facade responsible for handling “add offer to the project” call triggered  somewhere in a GUI. We want to ensure that static method Project.addOffer(long, Offer) will receive correct params when java.util.Map with user form input comes to the facade.add(params). This is unit test, so how Project.addOffer() works is out of scope. Thus we want to stub it. The most important is a GroovyMock(Project, global: true) statement. What it does is modifing Project class to behave like a Spock’s mock. GroovyMock() itself is a method inherited from Specification.  The global flag is necessary to enable mocking static methods. However when one comes to the need of mocking static method, author of Spock Framework advice to consider redesigning of implementation. It’s not a bad advice, I must say. Another important thing are assertions at then: block. First one checks an interaction, if the Project.addOffer() method was called exactly once, with a 1st argument equal to the projectId and some other param (we don’t have an object instance yet to assert anything about it). Right shit operator leads us to the stub which replaces original method implementation by such statement. As a good stub it does nothing. The original method definition has return type Offer. The stub needs to do the same. So an offer passed as the 2nd argument is just returned. Thanks to this we can assert about name property if it’s equal with the value from params. If no return was designed the name could be checked inside the stub Closure, prefixed with an assert keyword. Worth of  mentioning is that if you want to track interactions of original static method implementation without replacing it, then you should try using GroovySpy instead of GroovyMock. Unfortunately static methods declared at Java object can’t be treated in such ways. Though regular mocks and whole goodness of Spock can be used to test pure Java code, which is awesome anyway :)

No matter why, no matter is it a good idea. Sometimes one just wants to check or it’s necessary to be done. Mock a static method, woot? Impossibru!

In pure Java world it is still a struggle. But Groovy allows you to do that really simple. Well, not groovy alone, but with a great support of Spock.

Lets move on straight to the example. To catch some context we have an abstract for the example needs. A marketing project with a set of offers. One to many.

pipeline {
  agent any
  stages {
    stage('Unit Test') {
      steps {
        sh 'mvn clean test'
      }
    }
    stage('Deploy Standalone') {
      steps {
        sh 'mvn deploy -P standalone'
      }
    }
    stage('Deploy AnyPoint') {
      environment {
        ANYPOINT_CREDENTIALS = credentials('anypoint.credentials')
      }
      steps {
        sh 'mvn deploy -P arm -Darm.target.name=local-4.0.0-ee -Danypoint.username=${ANYPOINT_CREDENTIALS_USR}  -Danypoint.password=${ANYPOINT_CREDENTIALS_PSW}'
      }
    }
    stage('Deploy CloudHub') {
      environment {
        ANYPOINT_CREDENTIALS = credentials('anypoint.credentials')
      }
      steps {
        sh 'mvn deploy -P cloudhub -Dmule.version=4.0.0 -Danypoint.username=${ANYPOINT_CREDENTIALS_USR} -Danypoint.password=${ANYPOINT_CREDENTIALS_PSW}'
      }
    }
  }
}

 

So we test a

facade responsible for handling “add offer to the project” call triggered  somewhere in a GUI.
We want to ensure that static method Project.addOffer(long, Offer) will receive correct params when java.util.Map with user form input comes to the facade.add(params).
This is unit test, so how Project.addOffer() works is out of scope. Thus we want to stub it.

The most important is a GroovyMock(Project, global: true) statement.
What it does is modifing Project class to behave like a Spock’s mock.
GroovyMock() itself is a method inherited from Specification.  *The global flag is necessary to enable mocking static methods.*
However when one comes to the need of mocking static method, author of Spock Framework advice to consider redesigning of implementation. It’s not a bad advice, I must say.

Another important thing are assertions at then: block. First one checks an interaction, if the Project.addOffer() method was called exactly once, with a 1st argument equal to the projectId and some other param (we don’t have an object instance yet to assert anything about it).
Right shit operator leads us to the stub which replaces original method implementation by such statement.
As a good stub it does nothing. The original method definition has return type Offer. The stub needs to do the same. So an offer passed as the 2nd argument is just returned.
Thanks to this we can assert about name property if it’s equal with the value from params. If no return was designed the name could be checked inside the stub Closure, prefixed with an assert keyword.

Worth of  mentioning is that if you want to track interactions of original static method implementation without replacing it, then you should try using GroovySpy instead of GroovyMock.

Unfortunately static methods declared at Java object can’t be treated in such ways. Though regular mocks and whole goodness of Spock can be used to test pure Java code, which is awesome anyway :)

You May Also Like

OSGi Blueprint visualization

What is blueprint?Blueprint is a dependency injection framework for OSGi bundles. It could be written by hand or generated using Blueprint Maven Plugin. Blueprint file is only an XML describing beans, services and references. Each OSGi bundle could hav...

Multi phased processing in scala

Last time in our project we had to add progress bar for visualization of long time running process. Process was made of a few phases and we had to print in which phase we currently are. In first step we conclude that we need to create a class of Progre...

Simple trick to DRY your Grails controller

Grails controllers are not very DRY. It's easy to find duplicated code fragments in default generated controller. Take a look at code sample below. It is duplicated four times in show, edit, update and delete actions:

class BookController {
def show() {
def bookInstance = Book.get(params.id)
if (!bookInstance) {
flash.message = message(code: 'default.not.found.message', args: [message(code: 'book.label', default: 'Book'), params.id])
redirect(action: "list")
return
}
[bookInstance: bookInstance]
}
}

Why is it duplicated?

There is a reason for that duplication, though. If you move this snippet to a method, it can redirect to "list" action, but it can't prevent controller from further execution. After you call redirect, response status changes to 302, but after method exits, controller still runs subsequent code.

Solution

At TouK we've implemented a simple trick to resolve that situation:

  1. wrap everything with a simple withStoppingOnRender method,
  2. whenever you want to render or redirect AND stop controller execution - throw EndRenderingException.

We call it Big Return - return from a method and return from a controller at once. Here is how it works:

class BookController {
def show(Long id) {
withStoppingOnRender {
Book bookInstance = Book.get(id)
validateInstanceExists(bookInstance)
[bookInstance: bookInstance]
}
}

protected Object withStoppingOnRender(Closure closure) {
try {
return closure.call()
} catch (EndRenderingException e) {}
}

private void validateInstanceExists(Book instance) {
if (!instance) {
flash.message = message(code: 'default.not.found.message', args: [message(code: 'book.label', default: 'Book'), params.id])
redirect(action: "list")
throw new EndRenderingException()
}
}
}

class EndRenderingException extends RuntimeException {}

Example usage

For simple CRUD controllers, you can use this solution and create some BaseController class for your controllers. We use withStoppingOnRender in every controller so code doesn't look like a spaghetti, we follow DRY principle and code is self-documented. Win-win-win! Here is a more complex example:

class DealerController {
@Transactional
def update() {
withStoppingOnRender {
Dealer dealerInstance = Dealer.get(params.id)
validateInstanceExists(dealerInstance)
validateAccountInExternalService(dealerInstance)
checkIfInstanceWasConcurrentlyModified(dealerInstance, params.version)
dealerInstance.properties = params
saveUpdatedInstance(dealerInstance)
redirectToAfterUpdate(dealerInstance)
}
}
}