Showing posts with label stub. Show all posts
Showing posts with label stub. Show all posts

Sunday, August 29, 2010

How to mock/stub void methods using PowerMock

Ok, I had though that the previous post would be the last post in the how-to series, but there are so many features in PowerMock that I am tempted to write more about it :)

So, here comes another post on how to mock/stub void methods using PowerMock.

One would think why are void methods so special, that we need a post to explain them?

Well thats because they are void methods. They don't return anything. If you remember, from my earlier post, the syntax of stubbing any method with a non void return type is as follows

In the above example doSomething method of ServiceA instance returns a String.

But imagine what will be the syntax, if doSomething method's return type was void!

May be something like this?

But, if you think for a moment about the above syntax, we would realize that  

methods in java are not very happy to accept void as the argument type!

Effectively, in the above syntax the when method is taking void as one of the argument!

Well this is a problem. This cannot happen!  Hence, we need a special syntax to mock/stub void methods.

So without wasting any more time lets look at the code under test:

In our example we want to test the persistCustomer method of the CustomerController. This method simply calls persist method on the Customer instance passed as argument. Assuming that the persist method of the Customer class returns nothing if everything is fine and throws a RuntimeException if something horribly goes wrong.

We want to write the test case for both these scenarios. So how do we do it?

How will we test it - How do they do it!:

Well, there is always a way with PowerMock!

Our first scenario is to verify that the persistCustomer method returns true if everything goes fine.

PowerMock uses the following syntax to stub the void method to do nothing.


If we read the syntax in pure English it says,

Do nothing when persist method is invoked on customer instance

As simple as that! We are telling the mock customer object to do nothing when persist method is invoked.

Lets look at the test case:


Now the other scenario, we want to make sure that false is returned when an exception is thrown from the persist method of customer instance, but for that to happen we have to stub the persist method of customer to throw an exception.

This is how we do it:

Syntax in English:

Throw RuntimeException when persist method of customer instance is invoked.

Lets look at the test case:

Thats it! Well you see there always is an easy solution with PowerMock

Saturday, July 24, 2010

How to use custom argument matchers using PowerMock

We have come a long way and most likely this will be the last post in the series of how-to do stuff using PowerMock's (Mockito api) - Mocks on Steroid!

Some of the posts in the how-to series are more exotic then the others, but if you want to experience the real power of PowerMock, have a look at testing the UN-testable code.

In the previous post, we saw how we could use various argument matches, in situation when we don't know exactly what argument will be passed. Mockito already has a rich set of matchers but, if you think that is not enough we can write our own Matchers.

Why would you need them? Good question. In most cases the build in matchers are enough, but we might need custom matches when we want to make sure that a certain property of a certain class is set to a certain value.

Well did you understand that above sentence? No? Even I didn't understand that :)

As people say

Picture says a thousand words

my version of the same quote is

Code says everything

So lets look at the code under test.

Look at the argument passed to calculateChargeAmount method.  ServiceA's calculateChargeAmount passes a new instance of Calender to this method.

Of-course by now you already know how to test such a code. But since this post is about custom argument matchers, we will try to write a test for this method using the custom argument matcher.

But how do we write a custom argument matcher?

How will we test it - How do they do it!:

Well, turns out Mockito has a class called ArgumentMatcher. To create a custom matcher we extend the class ArgumentMatcher and override the matches method which returns a boolean.

If the matches method returns
  • true: means that the argument passed matches the criteria
  • false: means that the argument passed does not match the criteria
Along with this we need to use an argument matcher called argThat provided by Mockito. This argument matcher takes in an instance of our custom matcher, which will in-turn decide whether the argument passed matches our criteria.

Lets say in our example, we just want to make sure that the Calendar instance passed to the calculateChargeAmount method represents a date in the future.

This is how we could make use of the custom matcher in this case

Thats it folks! This is how we write custom argument matcher using Mockito.

It has been a pleasure doing this how-to series. I hope you guys have liked reading it as much as I have liked writing about it!

Monday, June 28, 2010

How to suppress fields with PowerMock

Now why would you want to do that! Lets look at the code straightaway.

Code under test:

The AccountDAO class has a "session" field, which has been initialized where its declared. Assuming that Session class in our example, is a wrapper over the the Hibernate Session class which talks to the database and does stuff for us.

BTW I couldn't agree more that its a terrible design!

So, basically what we want is to suppress the field "session" and instead use a stubbed Session instance.   Which means, we would stub out the getSession method, to write good unit-test case for the findAccount method.

So how do we suppress the field "session"

How would we test it - How do they do it!

The suppress method (which we had a look in the earlier post) can not only suppress the methods but can also suppress fields.


The Syntax:

What does the above syntax mean? Just read the line in plain English and that is exactly what it means!

Suppress the field of AccountDAO class called "session"

After this statement if we call getSession on any instance of AccountDAO it will always return null.

Q: But how can PowerMock do it?
A: Via byte code manipulation.  Remember our old friend @PrepareForTest(AccountDAO.class) annotation.

So we have solved one part of the problem. The next problem is to return a stubbed session instance when getSession method of AccountDAO is called. How can we do that?
A: Remember partial mocks via the spy method

That makes the problem look much simpler right?

So lets look at the test code:

Yes! We have managed to suppress a field for any given class.

Really, PowerMock's (using the Mockito api) keeps dazzling us with its Power!

Tuesday, May 25, 2010

How to partially mock a class and its private methods using PowerMock

Earlier, in the how-to series we had seen how-to mock constructors.  In this post we will have a look at how-to partially mock classes and even their private methods using PowerMocks - Mocks on Steroids!

Lets first look at the code to test before I start with my rambling

Code under test:

We want to write a test case to test method1 of ServiceA class.  ServiceA's method1 invokes method2.  method2 performs some complicated business logic - in this case creates an instance of ServiceB and invoked doBusinessOperation on that instance.

There are two approaches to test ServiceA's method1.


  • Write the test case to mock out the ServiceB's constructor and assert that doBusinessOperation method was invoked on the mocked ServiceB object.
  • Stub the method2 call!  Only verify that from method1 a call was made to the method2.

We already know how to write tests for the first approach.  Today we are more interested in looking at how do we write tests for the second approach.

Why would we ever choose the second approach over the first approach?  May be because method2 was already tested in some other test case.  Hence, we just want to make sure that method1 calls method2 with the right arguments.

So how do we partially mock ServiceA?

How will we test it - How do they do it!:

PowerMockito class provides a method called spy to create partial mock of a class.  This method takes an instance of the class that you want to partially mock as argument (in this case ServiceA).  Why? Because we want to invoke actual implementation of method1 and mock only method2.

Syntax

Then, we want to stubb out the method2 and return some dummy value.  This how its done

Notice the difference in the syntax then the regular when-theReturn syntax.  As, if we use the when-thenReturn syntax actual call to method2 will be made!  Why? Because PowerMocks does not know whether you are setting up an expectation on a partial mock or actually invoking the method.  Hence, be careful with partial mocks and choose the right syntax.

How to verify that the method was actually called?

No surprises here.

The full test case would look like:

A variation of the above example, what if the method2 was private?  Can we still stub it?  Of-course the right answer is YES!

Code under test:

How will we test it - How do they do it!:

Now, the above doReturn-when-method2 syntax wont work.  As method2 is private and is not accessible outside the scope of the class.  How do we stub it then?

Only change is, we pass in the name of the private method to stub as string argument to when method.  when method also accepts the var args array of arguments to the method2.

To verify that the private method2 was invoked use

Here also, instead of verify we use verifyPrivate and call a invoke method which accepts, name of the private method and its arguments.

Full test case would look like this:

Yes!  Thats it.  We have achieved what we intended to do!  PowerMock's is really a valuable tool to have in once arsenal!

How to mock constructors using PowerMock

In the how-to series today I will show how-to mock constructors using PowerMocks - Mocks on Steroids!.  In my previous post we saw how can we write unit-tests for mocking final methods and classes.

Requirement:

Again, taking a fictitious example, lets say that ServiceA creates an instance of ServiceB and invokes a businessOperation on ServiceB's instance.  ServiceB's constructor is evil and it throws a Exception.  We want to test this code.  Lets look at the code under test

As we can see, ServiceA's doSomething method create an instance of ServiceB class (by invoking a constructor with no arguments) and then invokes doBusinessOperation() method.  Looks like a simple class, but wait, have a look at ServiceB's constructor, its evil, it throws an exception!  Now how do we mock the constructor so that we can write a good tests case for ServiceA's doSomething method?  Simple, Using PowerMocks (Mockito api) :)

How will we test it - How do they do it!:

We have to use @PrepareForTest annotation with ServiceA class as, it instanciates ServiceB and we actually want to inject a stub on ServiceB so that we can verify that doBusinessOperation method was actually invoked.

Then, we use the whenNew method of PowerMockito to actually return a stub of ServiceB when a new instance of ServiceB is created using a no argument constructor.

Just read the above line in and then compare the syntax below

We can actually read the code in English and it does make a lot of sense!

Lets look at the test code now:

Piece of cake isn't!

Tuesday, May 11, 2010

Testing the Untestable code using PowerMock (Mockito api)

Taking inspiration from this excellent post by Johan Haleby, today I am going to jump a few gears and show you the real power of PowerMocks.  I will show you how can we write good unit-tests to test the untestable code!

We will continue the How-To series using PowerMocks (Mockito api) but today lets look at something more complicated.

You must be thinking, if the code is untestable then how can we write unit-tests?  But, that my friend is the real power of PowerMocks, we can write unit-tests for testing untestable code as well!

So What are we testing today.

Code to Test:

The code example is taken from one of the code samples of JMockit unit-testing framework (which by the way is another powerful unit-testing framework).  At first glance the code might not look as complicated, but make a note of the following points and then think how will you ever write a unit-test for doBusinessOperationXyz method?

  • The ServiceA class is final
  • It invokes a static method on Database class called find which returns a list
  • It then creates a new instance of ServiceB class and invokes computeTotal method, passing it items retrieved from Database.find call
  • ServiceB class is final as well
  • Invokes another static method on Database class called save, passing it the EntityX instance

Wow! it seems like a really tough class to test.  Lets move ahead and write some good unit-tests to test the above code!

How will we test it - How do they do it!:

You will be surprised to know that, we could write multiple unit-tests for the above code depending on what exactly we want to test!  How awesome!

Test Requirement 1:

Lets say we want to test that, the ServiceB was invoked to compute total.

Test Code:

As usual we have to annotate the TestCase with @RunWith annotation (go here know more on why we have to do so).

We can verify that computeTotal method was invoked on ServiceB instance via a mocked ServiceB object. But if you think about this for a moment, how can we do that?  Because ServiceA's doBusinessOperationXyz is actually instantiating ServiceB.

How can we suppress this behavior and inject our mocked ServiceB object?  Simple! via byte-code manipulation of ServiceA class :)

No no, don't worry, we don't have to do byte-code manipulation on our own, PowerMocks does that for us.  All we need to tell PowerMocks is for which classes we want to perform byte-code manipulation using the @PrepareForTest annotation (go here to know more about @PrepareForTest annotation).

Another point is we want to mock static methods in Database class as well.  Hence we have to use @PrepareForTest annotation for Database class as well.

And finally, note that since we want to mock ServiceB class, which is a final class we have to use @PrepareForTest annotation for ServiceB class as well.

Enough fluff, show me the stuff!

The unit-test code looks like this

Thats all folks!  We have successfully tested the Untestable code for our first requirement


Thats all folks!  We have successfully tested the Untestable code for our first requirement

Test Requirement 2:

Lets say we want to test that, the Database was used to save EntityX.

Test Code:

Now that you have read the post so far, this one must look straightforward to you!

The test-case looks like

Thats it!

Test Requirement 3:

Database find was invoked to get the list of EntityY

Test Code:

The test-case looks a lot similar to the previous example

I promise its not much after this.

Test Requirement 4:

Should verify that EntityY list returned from Database.find was used to computeTotal

Test Code:

This is the final one.

Test Requirement 5:

Should verify that computed total was set on EntityX instance

Test code:

Done!  Its pretty evident from the above examples that testing the Untestable code is pretty easy using PowerMocks (Mockito api)

Feedback, questions and comments are welcome as usual!

Monday, May 10, 2010

How to mock final methods and classes using PowerMock

This is the second post in the how-to series of using PowerMockito to write beautiful unit-tests. In my previous post we saw how can we write unit-tests for mocking static methods.

Today, I will demostrate how we can mock final class and final methods using PowerMocks (Mockito api) - Mocks on steroids!

Requirement:

I am going to take a ficticious example, were AnotherService class's invokeFinal() method invokes a final method on the instance of FinalService class which is a final class.

Code under test:

The final method doSomething in the final Class FinalService does nothing, just throws an exception.  AnotherService's invokeFinalMethod invokes doSomething method.

Most common mocking framework in the java world cannot mock final classes/methods because they are typically based on creating proxies.  Creating proxies for final classes is not possible as we cannot subclass a final classes.

So how we do we it in PowerMocks (Mockito api)?

How will we test it - How do they do it!:

Aha! Its tad simple.  We don't need to do anything special here.

We have to use @PrepareForTest annotation with FinalService so that PowerMocks can actually mock FinalService (Go Here for explanation on @PrepareForTest).  Next up, we need to create the stub of FinalService using the following code

Then, we have two approaches

I will show both the approaches

State based testing:

Interaction based testing:

Thats it!

It is needless to say that things look pretty easy with PowerMocks (Mockito api).  They look easy because they are easy with PowerMocks!  Yes! you can with PowerMocks (Mockito api)!

Feedback, questions and comments are always welcome.

Tuesday, May 4, 2010

How to mock static methods using PowerMock

OK, what are we up to today!  Today I will demonstrate how can we write unit test for a class that invokes a static method on another class to get some work done using PowerMocks (Mockito api) - Mocks on steroids! 

Yeah, Yeah I know, I know implementing functionality using static methods is bad and stuff like that.  But sometimes you just can't help it as its not in your control.  Hence, as all wise man (woman included) say, better deal with it!

We have not yet seen how we could mock normal classes and interface and directly looking at how to mock static methods.  Well as Mr. IronMan said

Sometimes you gotta run before you can walk.

Currently, I am working on a project that uses Spring Roo.  Roo uses a lot of AspetJ goodness.  It adds a lot of static methods to domain objects via AspectJ, making the domain objects richer.  For e.g. In a domain Class Customer it would add methods like findCustomer, findAllCustomers, countCustomers etc.  If you are interested in exploring more about Spring Roo, start here.

Spring Roo uses Spring MVC as the web layer.  Hence, I am going to take example of CustomerController (a controller that does CRUD on Customer domain object).  Enough history, lets see the real stuff!

Requirement:

When user requests to see the customer information, CustomerController should find the requested Customer and return that in the model.

Controller Code:

The controller code would look like

Not showing the Spring MVC specific annotations.  Here, findCustomer is the method added by Spring Roo to the Customer domain class.  This is a static method which  is invoked by CustomerController to get the requested Customer instance.  This is what we want to test. 

How will we test it - How do they do it!:

As I explained in my previous post, PowerMocks uses custom class-loader and byte-code manipulation to enable mocking of static methods.  PowerMocks does this by using the following annotations
  • @RunWith -- PowerMocks uses a custom Runner called PowerMockRunner.  This is done so that 
    • PowerMocks could show informative message if an exception is thrown from the test
    • PowerMocks could notify listeners of certain events.  For e.g. before the test methods start executing an event BeforeTestMethod is triggered.  Don't worry, if you don't understand this.  Its a little advanced stuff.  Just remember, that we need to use a Custom runner.
  • @PrepareForTest -- This annotation tells PowerMock to prepare certain classes for testing. Classes needed to be defined using this annotation are typically those that needs to be byte-code manipulated. This includes final classes, classes with final, private, static or native methods that should be mocked
That's about all the annotations you will need!  Next we will have to tell PowerMocks that we want to mock static methods of which class.  This is done using

We are saying PowerMocks (using the Mockito extension api) that we want to mock static methods in Customer class.

Next up, we have to stub the method we are interested in (we will be doing state based testing.  PowerMocks also supports interaction based testing, using the verify syntax.  Will not be showing it in this post though).  That's done like this

And then we can simply assert the customer is returned in the modelMap.  That's all!  Here's the complete test case code.

And we are done!  As we can see, PowerMocks (using the Mockito extension api) uses English like syntax, because of this test cases look a lot compact and are easier to read.

As usual, feedback, comments and complaints are always welcome!

Wednesday, April 28, 2010

PowerMock - Mocks on Steriods!

I have been developing software for some time now.  But have never seen a mocking/stubbing framework (in the java world) that is able to mock/stub everything!  literally everything!

People will argue that, the need to mock static methods, final classes/methods, mock static class, etc. is a sign of bad coding.  I couldn't agree more!  But time and again I have come to terms with a fact that there is a lot of legacy code people have already written and we are inevitably faced with situations where we have to work with it.  In such situations mocking framework like PowerMock is a real boon!

PowerMock basically extends other mocking libraries such as Mockito, EasyMocks and now even TestNGPowerMock uses a custom class-loader and byte-code manipulation to enable mocking of static methods, final classes/methods, etc.  Because of this, no changes need to be done to the IDE or continuous integration servers which simplifies adoption.

PowerMocks have the following capabilities

  • Extends various well known mocking frameworks like Mockito, EasyMocks and TestNG.  Hence, it has an extremely low learning curve if you are familiar with any of of those mocking libraries.
  • Can 
    • mock static methods
    • mock final methods
    • mock static classes
    • mock final classes
    • mock constructors
    • mock private methods
    • remove static initializes
    • partially mock a class i.e. create spy
    • Suppress methods
    • Suppress constructors
    • Suppress static initializes
    • Suppress fields!
    • On top of all this it can also mock/stub normal classes and interfaces :)
Wow! now that's what I call a mocking framework on steroids!

Well, if you like what you are reading and what to see some code in action, stay tuned in the next series of posts I will show working samples of how actually its done!

As usual, feedback, comments and complaints are always welcome!

Monday, April 26, 2010

How to use the mocks to verify behaviour in grails

As you can probably see, I am completely vella (word in Hindi which means jobless) today!  Have set a personal record of posting so many blogs in a single day!

Based on the feedback i have received, here's another post in the how-to series.  This one shows you how to create mocks, on which expectations could be set and finally verify that all expectations were satisfied.

For the sake of this post as well I will use our very old PersonController.

Lets take the example of my good old friend, YES the PersonController

Yes, you are right I am actually in love with PersonController :)

What are we testing - What are we upto today!:

PersonController will invoke save method on the PersonService to actually save the person.  We want to verify this behavior.

Controller Code:

Here's how the controller code looks like

We are specifically interested in mocking the personService.save() method.  Have already explained how to test rest of the code in my previous posts here and here.

How will we test it - How do they do it!:

GrailsUnitTestCase class provides a superb method call mockFor (to create mock objects!)  How simple is that!  Using mockFor method we could create mocks for any class.  We could set expectations on the mock and finally verify that all expectations are met.

The test case steps to tests the above code.
  1. Mock the PersonService using the mockFor method
  2. Set expectations on the PersonService
  3. Dependency inject the mocked personService into the controller instance.
  4. Invoke the controller code
  5. Verify all the expectations are met
Thats all.  Pretty easy ha!   
   
Test code looks like this:

Yes, that's all!  As we can see, grails adds extremely flexible and powerful mocking support.  Use it!

As usual feedback, comments and complaints are welcome!

Sunday, April 25, 2010

How to stub message method in a controller

Hello Gang!  Based on the feedback from all you guys, here's a post about how easily can we stub the message method while writing controller Unit tests.

Lets take the example of my good old friend, YES the PersonController

Requirement:

After saving a person user should be redirected to show view, with a flash message indicating user was saved successfully.

Controller Code:
We have seen similar code in the past lets look at it again

We are not interested in code showing the action required if errors are returned while saving a person (As we had already covered that here)

Only different between the earlier code and this one is the flash.message and the use of message method.

How will we test it - How do they do it!:

In the grails environment, a method called message is dynamically added to the instance of PersonController, but how do we write a unit test for this?

All our controller test cases have been extending ControllerUnitTestCase which adds a lot of utility methods and fields to the controller instance.  But unfortunately it does not stub out the message method.  Hence, to test the above code we will have to stub out the message method manually. How? remember metaClass technique from my earlier post we will apply it here as well.

  1. Stub out the save method (on the person instance ) to return true, using the metaClass of Person
  2. Add a dummy message method on the controller instance, again using the metaClass of controller
  3. Assert that flash.message was correctly set by the PersonController 
  4. Remember to remove the metaClass of Person using which we stubbed the save method using the GroovySystem class.  (For explanation on why is this necessary see this post)
   
Test code looks like this:

If you notice we didn't use removeMetaClass for the controller instance. Why? because our test case extends ControllerUnitTestCase which creates a new instance of the controller class under test (in this case PersonController)before every test case is run. And hence we don't bother to use the removeMetaClass for the controller instance.

That's all folks!  As we can see metaClass is a real boon for unit testing

As uaual feedback, comments and complaints are welcome as always!

Unit testing Grails Controller - Part - 3

Alright folks this is the third and final installment of Unit Testing Grails Controller series.

In the last post I explained how we could write a test case where controller returns a model that could be used by view to render itself.

In this post we will see how we could write tests for situations in which controller has to render a view (may be to show validation errors while saving a instance of domain class)

Tired of repeating, but will say it again anyways, taking an example of a controller that performs CRUD on Person domain class lets call it PersonController

Requirement:

If an error occurs while saving a person, controller should re-render the create view showing the error so that user can rectify the error and try again.

Controller Code:
The controller code that will do the job for us looks like

How will we test it - How do they do it!:

Again, in the grails environment, save method on a person instance will actually fire an insert statement, but do we really want to do that while writing a unit test for PersonController?  The right answer is NO.  10 Points if you get that right!

So what are we doing in the above code sample.
  1. Creating a person instance using the request parameters
  2. Try to save the person created in the previous step
  3. If save fails render the create view and return from there (Guard clause is an import pattern which deserves a post for itself)
  4. If save succeeds redirect user to show view.
We should have a unit-test, for each of the above steps.
We already know how to write test case for step 4 from the first post

Lets focus on the first three steps.  There are two ways in which we can test the above code.  A longer and a shorter way!  And yes you guessed it, I will show the longer way first :)

Method 1: 
  1. use mockDomain(Person) to add the save dynamic method to person instance
  2. From the test code, we could populate the params map with invalid values
  3. Those params would be used to construct the Person instance
  4. While saving the person instance constraints will be fired, which will fail because of invalid values
  5. This will cause the save method to return false and hence if condition will be satisfied causing the render to execute.
  6. ControllerUnitTestCase class provides us a convenient property called modelAndView using which we can assert that controller actually renders to the create view
The test class code to demonstrate the above method is as follows

Although we should have written another test case to assert that the model was correctly populate by the controller but for the sake of this blog I have shown the assert in single test case.

Now that you have the Grails power, don't go anywhere!  I promise, will not bore you for long.  Here's the Method 2 of testing the above code.

Method 2:
  1. Stub out the save method (on the person instance) to return false manually, using the metaClass of Person
  2. use the modelAndView property to assert that controller actually renders the create view
  3. Remember to remove the metaClass using which we stubbed the save method using the GroovySystem class.  If you don't do this then the metaClass setting will interfere with other tests that use the save method.  Because of this, some test cases could misteriously start failing when, run along with other tests and pass when run individually.  Such a situation is extremely difficult to debug and fix.  This is the single most common mistake people do while using metaClass.  Take my advice, Dont do it!
Short and simple isn't it.  lets look at the test code.

See its pretty easy to randomly add/stub methods using the metaClass.  Its a really powerful tool but as Spider Man's uncle Ben once said
With great power comes great responsibility!
use it responsibly!

Here, I conclude the three part series to demonstrate art of Unit Testing the grails controller

I hope you liked reading it as much as I liked writing it.  Feedback, Comments and Complaints are welcome as always!

Unit testing Grails Controller - Part - 2

As promised to my readers here's the second installment of Unit testing grails controller.

In my previous post  we had seen how can we test a situation where grails controller redirects user to a different action.

In the post we will focus on how we could test a situation where controller returns a model, which can be used by a view to render itself.

Again, as in the previous post for simplicity I am taking an example of a controller that performs CRUD on Person domain class lets call it PersonController

Requirement:
When user tries to view person's data,  controller should retrieve requested person's information and return it so that view can render itself.

Controller Code:
The controller code would look like

For simplicity I have not shown the code to handle a situations when person with the given id is not found.

How will we test it - How do they do it!:
Clearly, when above code is run in the Grails environment Person.get(personId) will actually fire a database query to get the person.  But when we are unit testing the controller we dont want to fire a database query.  Basically we want to test the PersonController in isolation.

Fortunately, grails provides a method called mockDomain.  This is an extremely powerful method added by the GrailsUnitTestCase class.  As the name suggests, it mock's any grails domain class (as simple as that :)).  This method adds dynamic methods such as save, get, various finder's etc. to Grails domain class.  For e.g. 

will add previously mentioned dynamic methods to Person class.  Which effectively means that we can simulate the behaviour of these methods without actually firing queries agains our database.  Which is what we wanted in the first place!

There are two overloaded versions of mockDomain method
 

This version behaves as if there are no records in the Person table. 

Second version is

This version behaves as if, each person instance found in the [List of people] represents one record in the person table.  Hence when you call Person.get(123) if the list contained a person with id 123, that person will be returned.

Enough Said!  Show me the code damn it!


The Test case class:
The test case can be written as
 

Thats all folks!  This is all we need to tests the controller method.

Stay tuned for next installment of Unit Testing Grails Controller!

In this post I have changed my style a little.  Explanation comes before the actual code.  Do give me feedback about this approach which one do you like and why?
Have some Fun!