englishteeth.co.uk

… the weblog of Ian “English Teeth” Robinson
  • rss
  • Home

Grails Unit Testing: How to mock a closure

Ian | August 29, 2008

I have found numerous resources on testing in grails, unit testing and Using MockFor and StubFor in groovy. However, given that closures are one of the key features of groovy, I found very little on how to accommodate them in testing.

The following is a simple controller with a list action that returns a set of Customer domain objects from a database and this action applies some simple filter criteria (thanks to this post I came across):

   def list = {
        def items

        if(!params.max) params.max = 10
        if(!params.sort) params.sort = "lastUpdated"
        if(!params.order) params.order= "desc"
        if (params?.filter) {
            def criteria = Customer.createCriteria()
            items = criteria.list(params) {
                or {
                        ilike ('surname', "%${params.filter}%")
                        ilike ('forename', "%${params.filter}%")
                        ilike ('emailAddress', "%${params.filter}%")
                }
            }
        }
        else {
            items = Customer.list (params)
        }

        render (view: 'list', model: [ customerList: items, filter:params.filter ], params: params)
    }

This action uses the Hibernate Criteria Builder to construct the query.

When unit testing Grails does not inject any of the dynamic methods and so these must be provided for. For this I covered the dynamic controller methods in the set up and tear down operations (thanks wholly to Glen Smith’s MockFor(March): Unit Testing Grails Controllers…

    def redirectParams
    def renderParams
    def params

    /** Setup metaclass fixtures for mocking. */
    void setUp() {

        params = [ : ]
        CustomerController.metaClass.getParams = { -> params }

        redirectParams = [ : ]
        CustomerController.metaClass.redirect = { Map args -> redirectParams = args  }

        renderParams= [ : ]
        CustomerController.metaClass.render = { Map args -> renderParams = args  }

    } 

    /** Remove metaclass fixtures for mocking. */
    void tearDown() {
        def remove = GroovySystem.metaClassRegistry.&removeMetaClass
        remove CustomerController
    }

The dynamic methods for the domain class I covered in the test where they were used.

    void testNoFilterReturnsList() {

        def testItems = [ 'x', 'y', 'z' ]

        params['filter'] = null ;

        // mock the static list and count methods
        Customer.metaClass.static.list = { Map params -> testItems } 

        CustomerController cc = new CustomerController()
        cc.list()

        assertNull renderParams.model.filter
        assertEquals testItems, renderParams.model.customerList

    }

This could hardly be simpler and is covered in much more detail elsewhere. Where I ran into difficulty was testing the the criteria was applied.

I wanted to provide a mock object for the org.hibernate.Criteria object returned for the domain.
def customerCriteria = new MockFor(org.hibernate.Criteria)
Defining expectations on the mock object is straight forward too, just demand it!
customerCriteria.demand.list { -> testItems }
Except that what ever I seemed to try would not match the signature of the call to list that I was trying to do in the filter test above.

Despite being a little elusive, the answer was simple enough. The closure defining the search criteria is a parameter to the call. There must be a list method declared with a signature along the lines of
def list (Map params, Closure criteria)(At least, that’s what I had to do in a test class to mimic that results I was seeing.)

So, to define a demand to match that… well, just treat it as such.

    void testFilterAppliedToCriteria() {

        def testItems = [ 'x', 'y', 'z' ]

        params['filter'] = 'search on something' ;

        def customerCriteria = new MockFor(org.hibernate.Criteria)
        customerCriteria.demand.list { Map params, Closure cls -> testItems }
        Customer.metaClass.static.createCriteria = { org.hibernate.Criteria }
        customerCriteria.use{
        	CustomerController cc = new CustomerController()
        	cc.list()

        	assertEquals params.filter, renderParams.model.filter
        	assertEquals testItems, renderParams.model.customerList
        }
    }

I continue to stumble through, though I’m becoming more convinced that I don’t know what I am doing.

Comments
4 Comments »
Categories
development
Tags
closures, grails, groovy, hibernate, testing
Comments rss Comments rss
Trackback Trackback

Grails ClassCastException for Application

Ian | August 21, 2008

Having persevered with mapping my existing database in grails, it actually made for much cleaner domain objects.

I never much liked when hibernate started creeping out of configuration and into the code via Java annotations, so on the same score, it was cathartic to remove the database aware gorm mappings from my domain classes.

Adding the hibernate configuration was straight forward and clean and tucked away in the conf/hibernate directory; an hibernate.cfg.xml file listing the mapping resources and an hbm.xml resource file for each entity.

All was going swimmingly until I was adding my last domain class; modelling an Application.

As soon as I wanted to “show” a particular Application I was getting a ClassCastException.

It would appear that I’m not the first to hit this, so luckily I didn’t have waste too much time trying to figure out why:

application/create throws java.lang.ClassCastException: Application cannot be cast to javax.servlet.ServletContext

Apparently…

there is a variable in the GSP binding called ‘application’ that is the ServletContext this gets overridden when you return the model from the controller

The bug is on create, but I guess as I am coming from the legacy database angle, I didn’t have to “create” before I tried to “show”.

Mmm.

Comments
No Comments »
Categories
development
Tags
domain, gorm, grails, hibernate, java
Comments rss Comments rss
Trackback Trackback

Grails on an existing database revisited

Ian | August 20, 2008

Some time ago I looked at what was necessary to have Grails work on an existing database rather than the green field scenario painted in most examples.

It seemed straight forward enough, but beyond curiosity, I didn’t have anything I was particularly trying to achieve, so I moved along.

Yesterday, once again messing around with grails, I found something I couldn’t seem to achieve via gorm.

Basically, I couldn’t define the column mapping for an embedded class (where instead of mapping classes onto separate tables a class can be “embedded” within the current table).

I had hoped it would be a straight forward as defining the column mappings in the embedded class definition, but unfortunately not. Any mappings appear to be ignored.

I tried in the embedding class. No. I even experimented with the embedded property, but that was a long shot I didn’t expect to work anyway.

It would seem I will have to define the mapping in the old fashioned hibernate configuration file way.

One useful thing I did find in this frustrating experiment is that the configuration setting …
dataSource {
logSql = "true"
}

… provides a more readable format than …
hibernate {
show_sql = "true"
}

Not a total loss then!

Comments
1 Comment »
Categories
development
Tags
db, gorm, grails, hibernate, sql
Comments rss Comments rss
Trackback Trackback

Scrollable tables, CSS and fetaures of IE6

Ian | August 18, 2008

I couldn’t leave this alone. A colleague was wrestling with some css to have a number scrollable tables within a larger scrolling area hold their column headers in place.

There were the plenty resources out there that nearly provided the solution, but each step had a draw back.

Did I mention that the target was IE6?

This post got us most of the way there.

Unfortunately, scrolling a table caused the header to bounce around horribly. Which through a bit of trial and error turned out to be caused by setting the background colour of the scrolling div containing the table. (Obvious! How didn’t I see that one straight off?)

Next there was the scroll bars.

overflow: scroll;

Causes both scrollbars to be always visible. Disabled if they don’t do anything,but always there.

overflow: auto;

Causes just the necessary scrollbar to show.

This was preferable for tables which were only ever going to have vertical scrolling. Unfortunately, when the table only had a couple of rows, there was a scrollbar sized gap on the right.

The fix for that…

div.scrollTableContainer table {
width: expression(offsetParent.clientWidth+"px");
}

A bit of javascript, dug up from here, to set the width to the visible width.

But these shorter tables also left blank space below them and as found before, we could not set the colour of this space without the horrible jumpy headers!

Searching around, if became apparent very quickly that css flickering in IE6 was a common problem with possible solutions.

  • No more IE6 background flicker
  • Fixing the abominable

But not quite… everything I found addressed the issues of images flickering, but although the causes of the flicker were the same, the jumping header as a side effect was not.

So, in order to have the desired colour while maintaining…

background-color: transparent;
background-repeat: repeat;

…was to add a small background gif of the desired colour.

No. Jumping headers are back! Seems that there is another IE6 bug whereby the the default background attachment is not implemented correctly.

background-image: url(colour.gif);
background-attachment: fixed;

Should handle that.

So in summary, we needed a bit of Scrolling HTML Table with Fixed Header, followed by a touch of No more IE6 background flicker and topped off with Everything you could possibly want to know about CSS Background Properties, including default values, browser support, targeting the DOM, and what to look for in CSS3.

Not much then.

Next time, I’ll mind my own business.

Comments
3 Comments »
Categories
development
Tags
css, html, java script
Comments rss Comments rss
Trackback Trackback

Freesat part 3

Ian | August 16, 2008

Done, bar the media center installation…

Safety first, I set up the area where the ladder was to go on Thursday evening. The main component of this was piece wood screwed into the pathway for the foot of the ladder to butt against.

I put the dish up on Friday evening, since the weather was nice.

Fixing the bracket
Dish roughly in place

Saturday defied the weather forecast and I was able to wire up the dish.

Alignment was remarkably swift and simple. As mentioned in my previous posts here and here, I’d read and re-read relevant sections of Martin Pickering e-book on numerous rainy evenings as well as this post on The Perfect Satellite Dish Alignment - a How To Guide, but I was still surprised.

Having used Dish Pointer to find my Azimuth and Elevation, I pointed the dish in roughly the right direction. I could hear the Olympics blaring from the tv attached to the old digibox, so I knew I’d locked on to the right satellite straight away. Then it was just a couple of horizontal adjustments to get the strongest tone on the satellite finder. I did a sanity check on the vertical and got a bit of an improvement there and finished off with the skew adjustment. I don’t think it could have taken much more than five minutes in total.


Signal on digibox

After that it was just a case of tidying up. Fitting the f-plugs on the dual shot gun cable and sealing the hole into the loft space.

Part of the installation aim was to replace a failing freeview box in the kitchen, so I browsed around for a SD freesat tuner to fill it’s space. I chose the bush, mainly as it was the cheapest and I could pick one up locally.

I came across Join Freesat web site in the course of all this, which was a quite interesting resource.

Bought, plugged in and tuned without any issues. WAF achieved so far at least; she felt the receiver looked better than the previous box and the picture seemed better too.

Comments
No Comments »
Categories
miscellaneous
Tags
freesat, freeview, media center, tv
Comments rss Comments rss
Trackback Trackback

« Previous Entries

Author

Ian Robinson is a relatively agile software engineer interested in things both sides of the object relational divide and beyond.

Categories

  • development (37)
  • miscellaneous (28)
  • music (7)
  • software (19)

What I'm Doing...

  • @noelfielding11 why are you in watching telly!? in reply to noelfielding11 2010-04-16
  • What was so good about Nick Drake? These "artists" are covering, music is spot on but no effect at all. Totally lacking the goose pimples. 2010-04-16
  • Some Ginger bloke's on telly covering Nick Drake in a mediocre style. 2010-04-16
  • More updates...

Posting tweet...

Powered by Twitter Tools.

Blogroll

  • Dan North
  • Dave Astels
  • Dave Wood
  • eirikso.com
  • Matt Raible
  • Object Mentor Blog
  • The Ancient Art of Programming
  • The Wisdom of Ganesh

Tags

active-mq architecture bauhaus css db eclipse esb festivals freesat gorm grails groovy hd hibernate htpc java jboss jms junit links mce media center mini music oracle osgi patterns pirsig plugins satellite soa software spring sql struts2 testing themes tools tv vmc web wordpress xml xpath xslt
rss Comments rss valid xhtml 1.1 design by jide powered by Wordpress get firefox