<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Intelligrape  Groovy &#38; Grails Blogs &#187; Unit Test</title>
	<atom:link href="http://www.intelligrape.com/blog/category/grails/unit-test-grails/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.intelligrape.com/blog</link>
	<description></description>
	<lastBuildDate>Thu, 02 Feb 2012 07:48:06 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<image>
			<title>Intelligrape  Groovy &amp; Grails Blogs</title>
			<url>http://www.intelligrape.com/blog/wp-content/uploads/2011/05/favicon2.ico</url>
			<link>http://www.intelligrape.com/blog</link>
			<width></width>
			<height></height>
			<description></description>
		</image>		<item>
		<title>Grails productivity enhancer. The unsung hero &#8216;grails interactive mode&#8217;</title>
		<link>http://www.intelligrape.com/blog/2011/11/30/grails-productivity-enhancer-the-unsung-hero-grails-interactive-mode/</link>
		<comments>http://www.intelligrape.com/blog/2011/11/30/grails-productivity-enhancer-the-unsung-hero-grails-interactive-mode/#comments</comments>
		<pubDate>Wed, 30 Nov 2011 11:18:52 +0000</pubDate>
		<dc:creator>Mohd Farid</dc:creator>
				<category><![CDATA[Grails]]></category>
		<category><![CDATA[Test]]></category>
		<category><![CDATA[Unit Test]]></category>
		<category><![CDATA[productivity]]></category>
		<category><![CDATA[tip]]></category>
		<category><![CDATA[trick]]></category>
		<category><![CDATA[Tricks]]></category>
		<category><![CDATA[unit-test]]></category>

		<guid isPermaLink="false">http://www.intelligrape.com/blog/?p=4501</guid>
		<description><![CDATA[Of late, I have been thinking about the popularity of grails interactive mode amongst developers. I found that though most of us are aware of this mode but we don't use it as often, as it should be.

</br>
<strong>Where should I use grails --interactive mode while developing in grails?</strong>
The answer may vary from person to person and the level of expertise. For me, I found it amazing while running my tests and creating artifacts. 
</br>
I shall describe the advantages that I found with interactive mode while running Unit Tests. Let us take an example here:

I have a class called PersonUtil which needs to be unit tested. I write a PersonUtilTests class for testing its functionality. In order to run this particular unit test, I can use the following command:
[java]grails test-app unit: PersonUtilTests[/java]
This takes approximately 20 secs on an average to run on my machine with a decent configuration. 

Alternatively, We can run it in interactive mode. What we need to do is 

[java] grails --interactive[/java]

This shall bring the grails infrastructure up and make it just ready to run commands. It takes around 5 seconds.
[java]Welcome to Grails 1.3.7 - http://grails.org/
Licensed under Apache Standard License 2.0
Grails home is set to: /opt/grails

Base Directory: /home/farid/grailsApplications/survey-app/ErServices
--------------------------------------------------------
Interactive mode ready. Enter a Grails command or type "exit" to quit interactive mode (hit ENTER to run the last command):

[/java]
Now, to test the app I can use the following command:
[java]
-------------------------------------------------------
Command TestApp completed in 2461ms
--------------------------------------------------------
Interactive mode ready. Enter a Grails command or type "exit" to quit interactive mode (hit ENTER to run the last command):
test-app unit: PersonUtilTests
[/java]

It took 15 seconds to run this for first time.
For subsequent runs, it took 2-4 seconds. Which is a clear advantage of 16 seconds for every run. These 16 seconds are no less than gem when you are in your "flow-state"( in concentration mode). 
<p>
While development, we make frequent changes to our code and therefore we need to run our unit tests multiple times. Every time I make a change and re run my unit test it takes 20 seconds through conventional grails test-app whereas it takes 3-4 seconds through interactive mode. 
 </p>

Earlier, I used to get frustrated while waiting for test cases to execute. This waiting time is one of the biggest factor that drives us from doing Test Driven Development.  
</br>
Just in case you have not tried it. Please give it a shot. Believe me, it's worth trying, you wont be disappointed!!! 
</br>
Mohd Farid
farid@intelligrape.com










]]></description>
			<content:encoded><![CDATA[<p>Of late, I have been thinking about the popularity of grails interactive mode amongst developers. I found that though most of us are aware of this mode but we don&#8217;t use it as often, as it should be.</p>
<p></br><br />
<strong>Where should I use grails &#8211;interactive mode while developing in grails?</strong><br />
The answer may vary from person to person and the level of expertise. For me, I found it amazing while running my tests and creating artifacts.<br />
</br><br />
I shall describe the advantages that I found with interactive mode while running Unit Tests. Let us take an example here:</p>
<p>I have a class called PersonUtil which needs to be unit tested. I write a PersonUtilTests class for testing its functionality. In order to run this particular unit test, I can use the following command:</p>
<pre class="brush: java;">grails test-app unit: PersonUtilTests</pre>
<p>This takes approximately 20 secs on an average to run on my machine with a decent configuration. </p>
<p>Alternatively, We can run it in interactive mode. What we need to do is </p>
<pre class="brush: java;"> grails --interactive</pre>
<p>This shall bring the grails infrastructure up and make it just ready to run commands. It takes around 5 seconds.</p>
<pre class="brush: java;">Welcome to Grails 1.3.7 - http://grails.org/
Licensed under Apache Standard License 2.0
Grails home is set to: /opt/grails

Base Directory: /home/farid/grailsApplications/survey-app/ErServices
--------------------------------------------------------
Interactive mode ready. Enter a Grails command or type &quot;exit&quot; to quit interactive mode (hit ENTER to run the last command):
</pre>
<p>Now, to test the app I can use the following command:</p>
<pre class="brush: java;">
-------------------------------------------------------
Command TestApp completed in 2461ms
--------------------------------------------------------
Interactive mode ready. Enter a Grails command or type &quot;exit&quot; to quit interactive mode (hit ENTER to run the last command):
test-app unit: PersonUtilTests
</pre>
<p>It took 15 seconds to run this for first time.<br />
For subsequent runs, it took 2-4 seconds. Which is a clear advantage of 16 seconds for every run. These 16 seconds are no less than gem when you are in your &#8220;flow-state&#8221;( in concentration mode). </p>
<p>
While development, we make frequent changes to our code and therefore we need to run our unit tests multiple times. Every time I make a change and re run my unit test it takes 20 seconds through conventional grails test-app whereas it takes 3-4 seconds through interactive mode.
 </p>
<p>Earlier, I used to get frustrated while waiting for test cases to execute. This waiting time is one of the biggest factor that drives us from doing Test Driven Development.<br />
</br><br />
Just in case you have not tried it. Please give it a shot. Believe me, it&#8217;s worth trying, you wont be disappointed!!!<br />
</br><br />
Mohd Farid<br />
farid@intelligrape.com</p>
]]></content:encoded>
			<wfw:commentRss>http://www.intelligrape.com/blog/2011/11/30/grails-productivity-enhancer-the-unsung-hero-grails-interactive-mode/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Initializations in Grails Unit Test Cases</title>
		<link>http://www.intelligrape.com/blog/2011/06/14/initializations-in-grails-unit-test-cases/</link>
		<comments>http://www.intelligrape.com/blog/2011/06/14/initializations-in-grails-unit-test-cases/#comments</comments>
		<pubDate>Tue, 14 Jun 2011 08:07:30 +0000</pubDate>
		<dc:creator>Imran Mir</dc:creator>
				<category><![CDATA[Grails]]></category>
		<category><![CDATA[Groovy]]></category>
		<category><![CDATA[Test]]></category>
		<category><![CDATA[Unit Test]]></category>
		<category><![CDATA[grails unit test]]></category>
		<category><![CDATA[grails unit test case setup initialization]]></category>
		<category><![CDATA[grails unit test initialization]]></category>
		<category><![CDATA[Spock setup]]></category>
		<category><![CDATA[Spock Unit test setup]]></category>

		<guid isPermaLink="false">http://www.intelligrape.com/blog/?p=3865</guid>
		<description><![CDATA[ Most of us have experienced how important the Unit test cases are for our code base. I feel the other thing that is equally important, is the speed at which we can write the unit test cases. In Unit Testing, initializing different objects in setup of the test case (e.g., while testing a method [...]]]></description>
			<content:encoded><![CDATA[<p> Most of us have experienced how important the Unit test cases are for our code base. I feel the other thing that is equally important, is the speed at which we can write the unit test cases. In Unit Testing, initializing different objects in setup of the test case (e.g., while testing a method which queries the database) can become a pain, especially when the objects to be initialized have many attributes and relationships. Grails/Spock have simplified initialization process for us. All we need to is to initialize just the required attributes of the objects, along with the <b>id</b> field,e.g., while testing a method of a class Student : </p>
<pre class="brush: java;">
class Student {
  String name
  String fathersName
  String address
  static belongsTo = [school: School]

 static constraints = {
    name(nullable: false)
    fathersName(nullable: false)
    address(nullable: false)
  }

  // METHOD TO BE TESTED
  List&lt;Student&gt; findMySchoolsStudentsWithNamesLike(String nameLike) {
    List&lt;Student&gt; students = Student.findAllBySchoolAndNameLike(this.school, '%' + nameLike + '%')
    return students
  }

}
</pre>
<p> To test the method, a Spock test case with the simplified initializations will be like:   </p>
<pre class="brush: java;">
 def &quot;My School students are retrieved correctly&quot;() {
    setup:
    School school = new School(id: 1)
    List&lt;Student&gt; students = (1..10).collect {new Student(id: it, name: &quot;name${it}&quot;, school: school)}
    mockDomain(Student, students)

    expect:
    students[0].findMySchoolsStudentsWithNamesLike('1').size() == 2
  }
</pre>
<p> Similar setup can work in Grail Unit test case.<br />
 Simplification of the initialization process has made Unit testing simpler and faster, thus allowing us to write more Unit test cases.</p>
<p>Cheers,<br />
Imran Mir<br />
imran@intelligrape.com</p>
]]></content:encoded>
			<wfw:commentRss>http://www.intelligrape.com/blog/2011/06/14/initializations-in-grails-unit-test-cases/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Exception Testing using Spock in grails</title>
		<link>http://www.intelligrape.com/blog/2011/05/04/exception-testing-using-spock-in-grails/</link>
		<comments>http://www.intelligrape.com/blog/2011/05/04/exception-testing-using-spock-in-grails/#comments</comments>
		<pubDate>Wed, 04 May 2011 06:01:33 +0000</pubDate>
		<dc:creator>Uday Pratap Singh</dc:creator>
				<category><![CDATA[Grails]]></category>
		<category><![CDATA[Test]]></category>
		<category><![CDATA[Unit Test]]></category>
		<category><![CDATA[exception test in spock]]></category>
		<category><![CDATA[exception testing in grails]]></category>
		<category><![CDATA[grails spock plugin]]></category>
		<category><![CDATA[testing in grails]]></category>
		<category><![CDATA[testing in spock]]></category>
		<category><![CDATA[testing using grails]]></category>

		<guid isPermaLink="false">http://www.intelligrape.com/blog/?p=3752</guid>
		<description><![CDATA[Testing was never so easy and intuitive before the use of Spock.  Earlier when I was using grails unit testing, it never attracted me to write more and more test cases but with Spock you always keen to test each and every line of your code, testing the exceptions is one of them. 
You [...]]]></description>
			<content:encoded><![CDATA[<p>Testing was never so easy and intuitive before the use of Spock.  Earlier when I was using grails unit testing, it never attracted me to write more and more test cases but with Spock you always keen to test each and every line of your code, testing the exceptions is one of them. </p>
<p>You can always test the exceptions in grails unit test as well but with Spock it looks more clean and more readable. For example you have a method which throws exception like</p>
<pre class="brush: java;">
String getUserType(int age){
    if(age&lt;=0){
        throw new MyException(&quot;Invalid age&quot;)
    }else if( age&gt;0 &amp;&amp; age&lt;50){
        return &quot;Young&quot;
    }else{
        return &quot;Old&quot;
    }
}
</pre>
<p>Now we will write the test case of this method for checking whether exception is thrown for invalid inputs or not.</p>
<pre class="brush: java;">
def &quot;exception should be thrown only for age less than or equal to 0&quot;{
    given:
        String type = getUserType(34)
    expect:
        type == &quot;Young&quot;
        notThrown(MyException)
    when:
        type = getUserType(0)
    then:
        MyException me = thrown()
        me.message == &quot;Invalid age&quot;
}
</pre>
<p>This is how we have tested whether exception is thrown for invalid input or not. </p>
<p><br/><br />
Hope it helps<br />
<br/><br />
## Uday Pratap Singh ##<br />
uday@intelligrape.com<br />
<a href="http://www.IntelliGrape.com/">http://www.IntelliGrape.com/</a><br />
<a href="http://in.linkedin.com/in/meudaypratap">http://in.linkedin.com/in/meudaypratap</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.intelligrape.com/blog/2011/05/04/exception-testing-using-spock-in-grails/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Interaction based testing using Spock in Grails</title>
		<link>http://www.intelligrape.com/blog/2011/04/07/interaction-based-testing-using-spock-in-grails/</link>
		<comments>http://www.intelligrape.com/blog/2011/04/07/interaction-based-testing-using-spock-in-grails/#comments</comments>
		<pubDate>Thu, 07 Apr 2011 12:08:17 +0000</pubDate>
		<dc:creator>Uday Pratap Singh</dc:creator>
				<category><![CDATA[Grails]]></category>
		<category><![CDATA[Test]]></category>
		<category><![CDATA[Unit Test]]></category>
		<category><![CDATA[interaction test in spock]]></category>
		<category><![CDATA[spock test in grails]]></category>
		<category><![CDATA[spock testing grails plugin]]></category>
		<category><![CDATA[test method invocation]]></category>

		<guid isPermaLink="false">http://www.intelligrape.com/blog/?p=3512</guid>
		<description><![CDATA[In my recent project we are using spock test cases to test our application and spock really made it easy for us to test those things we were not able to test in Grails Unit Test or testing such things dont look so intuitive in Grails Unit tests . One of the powerful method of [...]]]></description>
			<content:encoded><![CDATA[<p>In my recent project we are using spock test cases to test our application and spock really made it easy for us to test those things we were not able to test in Grails Unit Test or testing such things dont look so intuitive in Grails Unit tests . One of the powerful method of spock testing is interaction based testing, which allow us to test whether the call is made to some other method with the defined parameters and it also tests how many calls are made to the other method.</p>
<p>The email sending perfectly fits into this example. So you have mail sending plugin in your application and one of your method sends mail to the users like following</p>
<pre class="brush: java;">
class EmailService {
def asynchronousMailService

public sendMail(String to, String from, String subject, String body) {
    try {
      asynchronousMailService.sendAsynchronousMail {
        to to
        subject subject
        body to
        from from
      }
    }
    catch (Throwable t) {
      log.error(&quot;Exception while sending email to user ${to}, Exception is ${t.getStackTrace()}&quot;)
    }
  }
}
</pre>
<p>and you have a method which calls this method</p>
<pre class="brush: java;">
class UserService {

def emailService

void sendActivationMail(User user){
    emailService.sendMail(user.email,&quot;admin@admin.com&quot;,&quot;Your account is activated&quot;, &quot;Congratulation now you can login&quot;)

  }

}
</pre>
<p>Now when you are testing sendActivationMail method you would like to can verify whether the call is made to emailService or not by using spock interaction based testing. You will write your test case something like</p>
<pre class="brush: java;">
def &quot;account activation mail sent to user&quot;(){
setup:
UserService userService = new UserService()

def emailService = Mock(EmailService)  // As we are not testing email service, we mocked the emailService
emailService.sendMail(_,_,_,_) &gt;&gt; true  //This will ensure to return true for any argument passed for sendMail method
userService.emailService = emailService

User user = new User(email : &quot;testUser@gmail&quot;)

when:
userService.sendActivationMail(user)

then:
1*emailService.sendMail(&quot;testUser@gmail&quot;,&quot;admin@admin.com&quot;,&quot;Your account is activated&quot;, &quot;Congratulation now you can login&quot;)

}
</pre>
<p>The then block ensures that the exactly 1 call is made to sendMail method with exactly the same arguments.<br />
We can have other use cases for interaction based testing like making calls to external APIs, logging different statements in different conditions.</p>
<p><br/><br />
Hope it helps<br />
<br/><br />
## Uday Pratap Singh ##<br />
uday@intelligrape.com<br />
<a href="http://www.IntelliGrape.com/">http://www.IntelliGrape.com/</a><br />
<a href="http://in.linkedin.com/in/meudaypratap">http://in.linkedin.com/in/meudaypratap</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.intelligrape.com/blog/2011/04/07/interaction-based-testing-using-spock-in-grails/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Grails Unit test case for cookies</title>
		<link>http://www.intelligrape.com/blog/2011/03/03/grails-unit-test-case-with-cookies/</link>
		<comments>http://www.intelligrape.com/blog/2011/03/03/grails-unit-test-case-with-cookies/#comments</comments>
		<pubDate>Thu, 03 Mar 2011 15:42:49 +0000</pubDate>
		<dc:creator>Uday Pratap Singh</dc:creator>
				<category><![CDATA[Grails]]></category>
		<category><![CDATA[Test]]></category>
		<category><![CDATA[Unit Test]]></category>
		<category><![CDATA[add cookies in grails unit test]]></category>
		<category><![CDATA[cookies in grails mocked request]]></category>
		<category><![CDATA[test cookies in grails]]></category>
		<category><![CDATA[test cookies in grails spock]]></category>

		<guid isPermaLink="false">http://www.intelligrape.com/blog/?p=3201</guid>
		<description><![CDATA[In one of my project we were reading the cookies so that we could do the processing accordingly. Now reading the cookie is easy but writing a unit test case for that action was little bit tricky for me because I wanted to test the behavior in case of when I find the cookie and [...]]]></description>
			<content:encoded><![CDATA[<p>In one of my project we were reading the cookies so that we could do the processing accordingly. Now reading the cookie is easy but writing a unit test case for that action was little bit tricky for me because I wanted to test the behavior in case of when I find the cookie and when there is no desired cookie in the request. So the question was how to add cookie into the mocked request.</p>
<p>To do this I did the following in my unit test setup</p>
<pre class="brush: java;">
Cookie cookie = new Cookie(&quot;APPNAME&quot;, &quot;ABCD&quot;)
mockRequest.cookies = [cookie].toArray()
</pre>
<p>Now I can test my action easily <img src='http://www.intelligrape.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> .<br />
<br/><br />
Hope it helps<br />
<br/><br />
## Uday Pratap Singh ##<br />
uday@intelligrape.com<br />
<a href="http://www.IntelliGrape.com/">http://www.IntelliGrape.com/</a><br />
<a href="http://in.linkedin.com/in/meudaypratap">http://in.linkedin.com/in/meudaypratap</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.intelligrape.com/blog/2011/03/03/grails-unit-test-case-with-cookies/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Load codecs in Unit tests using Groovy Grails</title>
		<link>http://www.intelligrape.com/blog/2011/02/23/load-codecs-in-unit-tests-using-groovy-grails/</link>
		<comments>http://www.intelligrape.com/blog/2011/02/23/load-codecs-in-unit-tests-using-groovy-grails/#comments</comments>
		<pubDate>Wed, 23 Feb 2011 08:00:19 +0000</pubDate>
		<dc:creator>Salil</dc:creator>
				<category><![CDATA[Grails]]></category>
		<category><![CDATA[Groovy]]></category>
		<category><![CDATA[Unit Test]]></category>

		<guid isPermaLink="false">http://www.intelligrape.com/blog/?p=3145</guid>
		<description><![CDATA[This post is all about enabling codecs (like encodeAsURL, decodeURL, etc) in your Grails Unit tests. I am assuming that you are already familiar with writing unit tests.

Scenario:
In our application code, if we have something like below:

      String serviceUrl = &#34;http://example.com/service&#34;
      String username = &#34;usernameStr&#34;
 [...]]]></description>
			<content:encoded><![CDATA[<p>This post is all about enabling codecs (like encodeAsURL, decodeURL, etc) in your Grails Unit tests. I am assuming that you are already familiar with writing unit tests.<br />
<br/></p>
<p>Scenario:<br />
In our application code, if we have something like below:</p>
<pre class="brush: groovy;">
      String serviceUrl = &quot;http://example.com/service&quot;
      String username = &quot;usernameStr&quot;
      String password = &quot;passwordvalue&quot;
      String urlStr = &quot;${serviceUrl}?u=${username.encodeAsURL()}&amp;p=${password.encodeAsURL()}..&quot;
</pre>
<p>Above code works very well when we run the application or even Integration tests. As we know that Codecs are automatically injected by Grails when application starts up.<br />
<br/></p>
<p><b>Problem</b>:<br />
When we use this code in our Unit Tests, it won&#8217;t work. Reason, Unit tests do not load Grails specific environment automatically. We have to mock or load the things (whatever required by test).<br />
<br/></p>
<p><b>Solution</b>:<br />
GrailsUnitTestCase class provides a method loadCodec(CodecClass). So here, to make encodeAsURL() working in our Unit tests, we just need add following line of code in our test (setup method).</p>
<pre class="brush: groovy;">
      loadCodec(URLCodec)
</pre>
<p><br/></p>
<p>That&#8217;s it. Rest of the work will be taken care by Grails <img src='http://www.intelligrape.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p>So whatever codec you need to load, just invoke loadCodec method with required codecClass in argument.</p>
<p>Your comments are always Welcome. Please post if you have any!<br />
<br/></p>
<p><br/><br />
Cheers!<br />
Salil Kalia<br />
Salil [at] IntelliGrape [dot] com<br />
<a href="http://twitter.com/salil_kalia" target='_blank'>Twitter</a> <a href="http://in.linkedin.com/in/salilkalia" target='_blank'>LinkedIn</a> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.intelligrape.com/blog/2011/02/23/load-codecs-in-unit-tests-using-groovy-grails/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Testing custom validator in grails unit test case</title>
		<link>http://www.intelligrape.com/blog/2010/11/14/testing-custom-validator-in-grails-unit-test-case/</link>
		<comments>http://www.intelligrape.com/blog/2010/11/14/testing-custom-validator-in-grails-unit-test-case/#comments</comments>
		<pubDate>Sun, 14 Nov 2010 13:31:01 +0000</pubDate>
		<dc:creator>Vishal Sahu</dc:creator>
				<category><![CDATA[Grails]]></category>
		<category><![CDATA[Groovy]]></category>
		<category><![CDATA[Test]]></category>
		<category><![CDATA[Unit Test]]></category>

		<guid isPermaLink="false">http://www.intelligrape.com/blog/?p=2092</guid>
		<description><![CDATA[Hi,
In my recent grails project, i needed to write unit test cases for testing custom validators which i created in command objects. To test validators, there is a method provided by grails &#8220;mockForConstraintsTests()&#8221; for validating constraints on Domain as well as Command-Object fields.
Let us take a scenario where we needed to use command object for [...]]]></description>
			<content:encoded><![CDATA[<p>Hi,</p>
<p>In my recent grails project, i needed to write unit test cases for testing custom validators which i created in command objects. To test validators, there is a method provided by grails &#8220;mockForConstraintsTests()&#8221; for validating constraints on Domain as well as Command-Object fields.</p>
<p>Let us take a scenario where we needed to use command object for user registration form. There are various fields in the class which include fields password and confirmPassword also. Now i want to validate that the value of password and confirm password should be same before saving it to the database.<br />
<br/><br />
I created custom validator for this which looks like.</p>

<div class="wp_syntax"><div class="code"><pre class="groovy">&nbsp;
  password<span style="color: #66cc66;">&#40;</span>nullable: <span style="color: #000000; font-weight: bold;">false</span>, blank: <span style="color: #000000; font-weight: bold;">false</span>, minSize: <span style="color: #cc66cc;">6</span><span style="color: #66cc66;">&#41;</span>
  confirmPassword<span style="color: #66cc66;">&#40;</span>nullable: <span style="color: #000000; font-weight: bold;">false</span>, blank: <span style="color: #000000; font-weight: bold;">false</span>, validator: <span style="color: #66cc66;">&#123;</span>val, obj -<span style="color: #66cc66;">&gt;</span>
            obj.<span style="color: #006600;">properties</span><span style="color: #66cc66;">&#91;</span><span style="color: #ff0000;">'password'</span><span style="color: #66cc66;">&#93;</span> <span style="color: #66cc66;">==</span> val
 <span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#41;</span></pre></div></div>

<p>The unit test which i write for this is like :-</p>

<div class="wp_syntax"><div class="code"><pre class="groovy"><span style="color: #993333;">void</span> testUserPasswordConstraints<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
&nbsp;
        mockForConstraintsTests<span style="color: #66cc66;">&#40;</span>UserCommandObject<span style="color: #66cc66;">&#41;</span>
        UserCommandObject uco <span style="color: #66cc66;">=</span> <span style="color: #000000; font-weight: bold;">new</span> UserCommandObject<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>
        uco.<span style="color: #006600;">password</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;abcde&quot;</span>
        uco.<span style="color: #006600;">confirmPassword</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;xyz&quot;</span>
        uco.<span style="color: #006600;">validate</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>
        assertNotNull<span style="color: #66cc66;">&#40;</span>uco.<span style="color: #006600;">errors</span><span style="color: #66cc66;">&#91;</span><span style="color: #ff0000;">&quot;confirmPassword&quot;</span><span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">&#41;</span>  
<span style="color: #808080; font-style: italic;">// Validation message for password and confirmPassword field do not match</span>
&nbsp;
 <span style="color: #66cc66;">&#125;</span></pre></div></div>

<p>So, by using &#8216;mockForConstraintsTests()&#8217; method we can easily write test cases for testing constraints and custom validators for domain as well as command-object fields.It helped me a lot.<br />
<br/><br />
Hope this helps.</p>
<p>Vishal Sahu<br />
vishal@intelligrape.com<br />
<a href="http://www.intelligrape.com">www.intelligrape.com</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.intelligrape.com/blog/2010/11/14/testing-custom-validator-in-grails-unit-test-case/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Tips for Agile Development with Unit Testing approach.</title>
		<link>http://www.intelligrape.com/blog/2010/07/14/tips-for-agile-development-with-unit-testing-approach/</link>
		<comments>http://www.intelligrape.com/blog/2010/07/14/tips-for-agile-development-with-unit-testing-approach/#comments</comments>
		<pubDate>Wed, 14 Jul 2010 17:22:59 +0000</pubDate>
		<dc:creator>Salil</dc:creator>
				<category><![CDATA[Grails]]></category>
		<category><![CDATA[Groovy]]></category>
		<category><![CDATA[Test]]></category>
		<category><![CDATA[Unit Test]]></category>
		<category><![CDATA[agile]]></category>
		<category><![CDATA[APIs]]></category>
		<category><![CDATA[coding-practices]]></category>
		<category><![CDATA[unit-test]]></category>

		<guid isPermaLink="false">http://www.intelligrape.com/blog/?p=1269</guid>
		<description><![CDATA[This is more towards the best practices and my experiences for developing an application at a faster rate.
In my current project, we are using many different APIs (for external services). And usually it takes time to explore, implement and then stabilize the application. Also, it&#8217;s not over once you stabilize your APIs based code. Because [...]]]></description>
			<content:encoded><![CDATA[<p>This is more towards the best practices and my experiences for developing an application at a faster rate.</p>
<p>In my current project, we are using many different APIs (for external services). And usually it takes time to explore, implement and then stabilize the application. Also, it&#8217;s not over once you stabilize your APIs based code. Because there are possibilities to have unexpected results such as server side errors, broken request, broken response, etc. Also you never know when Service provider makes some changes and your code breaks.</p>
<p>Well, here are some tips which really helped me to achieve faster implementation and more stable application (esp. when working with third party APIs).</p>
<p><strong>TRY TO MAKE YOUR CODE UNIT TESTABLE</strong> as much as possible.</p>
<p>1. Create Service layer for API based implementation. Keep this service layer independent from other application. So that you should run it without any other dependency.</p>
<p>2. Try to make small chunks of code (in form of methods) with least dependency on external things.<br />
Avoid Domain/Database/Environment specific code. In other words, don&#8217;t put any kind of framework specific dependency. In some cases you can&#8217;t avoid. But try to avoid as much as possible. Because it could lead to integration testing and which again takes more time. Unit test is the fastest way to check your code stability.</p>
<p>3. In case you have some dependencies (and that can not be avoided) &#8211; Try to mock it up. In many cases it&#8217;s possible. If you are using Grails/Groovy kind of framework/language &#8211; you have an edge to take an advantage of meta-programming.</p>
<p>4. There is no specific way to do this. But it comes with practice. You can follow above tips to implement your Service Layer Code. And then create unit tests &#8211; invoke your API based service methods. And run it. Wow.. that&#8217;s it.</p>
<p><strong>Advantages:</strong><br />
If there&#8217;s any kind of changes (from service provider), that can break your application&#8217;s functionality, test driven development will work as a &#8220;Life Saver&#8221;. It can tell you where&#8217;s the problem and why it happened. And you can make appropriate changes to stabilize it again.</p>
<p><strong>Same thing implements when you develop a new feature</strong>. Unit Test Case helps you see the results in few seconds. Instead of waiting for 10-15 minutes (until application starts).</p>
<p>Isn&#8217;t it cool?</p>
<p>I really appreciate this approach. Hope others will also use it.</p>
<p>Thanks<br />
Salil Kalia</p>
]]></content:encoded>
			<wfw:commentRss>http://www.intelligrape.com/blog/2010/07/14/tips-for-agile-development-with-unit-testing-approach/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Grails unit testing for beginners</title>
		<link>http://www.intelligrape.com/blog/2010/07/14/grails-unit-testing-for-beginners/</link>
		<comments>http://www.intelligrape.com/blog/2010/07/14/grails-unit-testing-for-beginners/#comments</comments>
		<pubDate>Wed, 14 Jul 2010 15:12:28 +0000</pubDate>
		<dc:creator>Imran Mir</dc:creator>
				<category><![CDATA[Grails]]></category>
		<category><![CDATA[Groovy]]></category>
		<category><![CDATA[Test]]></category>
		<category><![CDATA[Unit Test]]></category>
		<category><![CDATA[grails unit test]]></category>
		<category><![CDATA[unit test for beginners in grails]]></category>

		<guid isPermaLink="false">http://www.intelligrape.com/blog/?p=1241</guid>
		<description><![CDATA[Ques: How is unit testing different from integration testing ?
Ans: Integration tests need to bring up the whole grails environment.They talk to the database. All the dynamic GORM methods and properties are available here. Unit testing are small focused, fast loading tests that do not load supporting components.
Ques: How can I unit test a method [...]]]></description>
			<content:encoded><![CDATA[<p><em>Ques: How is unit testing different from integration testing ?</em></p>
<p>Ans: Integration tests need to bring up the whole grails environment.They talk to the database. All the dynamic GORM methods and properties are available here. Unit testing are small focused, fast loading tests that do not load supporting components.</p>
<p><em>Ques: How can I unit test a method in a service ?</em></p>
<p>Ans: You would need to follow these simple steps:</p>
<p>Suppose you want to write a unit test case for a someFunction() in MyService:</p>
<blockquote>

<div class="wp_syntax"><div class="code"><pre class="groovy"><span style="color: #000000; font-weight: bold;">class</span> MyService <span style="color: #66cc66;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #aaaadd; font-weight: bold;">String</span> myFunction<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
      <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #ff0000;">&quot;testString&quot;</span>
    <span style="color: #66cc66;">&#125;</span>
  <span style="color: #66cc66;">&#125;</span></pre></div></div>

<blockquote><p>-&gt; Create Unit Test File : grails create-unit-test com.intelligrape.xxx.MyService. It will create the test file in the folder <strong>/test/unit</strong><br />
-&gt; Write a testcase function<br />
-&gt; Create an object of MyService<br />
-&gt; Call the function and make assertions</p>
<blockquote>

<div class="wp_syntax"><div class="code"><pre class="groovy"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> testMyFunction<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">def</span> myService <span style="color: #66cc66;">=</span> <span style="color: #000000; font-weight: bold;">new</span> MyService<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>
    <span style="color: #aaaadd; font-weight: bold;">String</span> string <span style="color: #66cc66;">=</span> myService.<span style="color: #006600;">myFunction</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>
    assertEquals <span style="color: #ff0000;">&quot;testString&quot;</span>, string
  <span style="color: #66cc66;">&#125;</span></pre></div></div>

</blockquote>
<p><em>Ques: I am saving an object from this function. How can I test that ?</em></p>
<blockquote>

<div class="wp_syntax"><div class="code"><pre class="groovy"> <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> myFunction<span style="color: #66cc66;">&#40;</span><span style="color: #993333;">int</span> number, <span style="color: #aaaadd; font-weight: bold;">String</span> name<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
    MyDomainClass object <span style="color: #66cc66;">=</span> <span style="color: #000000; font-weight: bold;">new</span> MyDomainClass<span style="color: #66cc66;">&#40;</span>age: number, name: name<span style="color: #66cc66;">&#41;</span>
    object.<span style="color: #006600;">save</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>
  <span style="color: #66cc66;">&#125;</span></pre></div></div>

</blockquote>
<p>Ans: Its pretty simple. You would first need to mock the domain class whose object is being saved.</p>
<blockquote>

<div class="wp_syntax"><div class="code"><pre class="groovy">   <span style="color: #000000; font-weight: bold;">def</span> instances <span style="color: #66cc66;">=</span> <span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span>
   <span style="color: #000000; font-weight: bold;">def</span> myTestDomain <span style="color: #66cc66;">=</span> mockDomain<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">'MyDomainClass'</span>,instances<span style="color: #66cc66;">&#41;</span></pre></div></div>

</blockquote>
<p><em> instances</em> will serve as a cache of objects. Right now it contains no object. But when you call the save method from the function to be tested, it will automatically put that object in this cache. So, we can make assertions against this cache. Just to remind you, no database communication occurs during the unit testing.</p>
<blockquote>

<div class="wp_syntax"><div class="code"><pre class="groovy"> <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> testMyFunction<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">def</span> instances <span style="color: #66cc66;">=</span> <span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span>
    <span style="color: #000000; font-weight: bold;">def</span> myTestDomain <span style="color: #66cc66;">=</span> mockDomain<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">'MyDomainClass'</span>, instances<span style="color: #66cc66;">&#41;</span>
    <span style="color: #000000; font-weight: bold;">def</span> myService <span style="color: #66cc66;">=</span> <span style="color: #000000; font-weight: bold;">new</span> MyService<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>
    <span style="color: #aaaadd; font-weight: bold;">String</span> string <span style="color: #66cc66;">=</span> myService.<span style="color: #006600;">myFunction</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">30</span>, <span style="color: #ff0000;">'myName'</span><span style="color: #66cc66;">&#41;</span>
    assertEquals <span style="color: #cc66cc;">1</span>, instances.<span style="color: #663399;">size</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>
  <span style="color: #66cc66;">&#125;</span></pre></div></div>

</blockquote>
<p><em>Ques: What does this <strong>mockDomain</strong></em><em> do ?</em></p>
<p>Ans: mockDomain is a method of GrailsUnitTestCase, that helps to mock a domain class. mockDomain also mocks most of the injected methods of the domain class like, save(), validate(),delete(),get() and many others. But there are many methods it does not mock,e.g., createCriteria,find,findAll,withTransaction and many others.</p>
<p><em>Ques: That was great. But now my function uses some other service to do some job. How can I test that ?</em></p>
<blockquote>

<div class="wp_syntax"><div class="code"><pre class="groovy">  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> myFunction<span style="color: #66cc66;">&#40;</span><span style="color: #aaaadd; font-weight: bold;">String</span> empId<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
    <span style="color: #aaaadd; font-weight: bold;">String</span> name <span style="color: #66cc66;">=</span> otherService.<span style="color: #006600;">someOtherFunction</span><span style="color: #66cc66;">&#40;</span>empId<span style="color: #66cc66;">&#41;</span>
    MyDomainClass object <span style="color: #66cc66;">=</span> <span style="color: #000000; font-weight: bold;">new</span> MyDomainClass<span style="color: #66cc66;">&#40;</span>name: name<span style="color: #66cc66;">&#41;</span>
    object.<span style="color: #006600;">save</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>
  <span style="color: #66cc66;">&#125;</span></pre></div></div>

</blockquote>
<p>Ans: In this case you would need to mock both, other service as well as the method which is called.</p>
<blockquote>

<div class="wp_syntax"><div class="code"><pre class="groovy"><span style="color: #993333;">void</span> testMyFunction<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">def</span> otherService <span style="color: #66cc66;">=</span> mockFor<span style="color: #66cc66;">&#40;</span>OtherService<span style="color: #66cc66;">&#41;</span>
    otherService.<span style="color: #006600;">demand</span>.<span style="color: #006600;">someOtherFunction</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>empId-<span style="color: #66cc66;">&amp;</span>gt<span style="color: #66cc66;">;</span> <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #ff0000;">&quot;testName&quot;</span><span style="color: #66cc66;">&#125;</span>
    <span style="color: #000000; font-weight: bold;">def</span> myService <span style="color: #66cc66;">=</span> <span style="color: #000000; font-weight: bold;">new</span> MyService<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>
    myService.<span style="color: #006600;">otherService</span> <span style="color: #66cc66;">=</span> otherService.<span style="color: #006600;">createMock</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>
    <span style="color: #aaaadd; font-weight: bold;">String</span> string <span style="color: #66cc66;">=</span> myService.<span style="color: #006600;">myFunction</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">30</span>, <span style="color: #ff0000;">'myName'</span><span style="color: #66cc66;">&#41;</span>
    assertEquals <span style="color: #cc66cc;">1</span>, instances.<span style="color: #663399;">size</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #66cc66;">&#125;</span></pre></div></div>

</blockquote>
<p><em>Ques: What does this mockFor method do ?</em></p>
<p>Ans: It is a method that is used to mock a dependency. We can mock services and its methods with the help of this. The <em><strong>demand</strong></em> method of the object returned by the method can be used to mock different methods of the mockedInstance. We can also specify the number of times the function is actually called in the function.</p>
<blockquote>

<div class="wp_syntax"><div class="code"><pre class="groovy"> otherService.<span style="color: #006600;">demand</span>.<span style="color: #006600;">someOtherFunction</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">1</span>..<span style="color: #cc66cc;">2</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>empId<span style="color: #66cc66;">;</span> <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #ff0000;">&quot;testName&quot;</span><span style="color: #66cc66;">&#125;</span></pre></div></div>

</blockquote>
<p>Here, it means someOtherFunction() will be called not more than 2 times in the function.</p>
<p>Hope this helps.<br />
Imran Mir<br />
imran@intelligrape.com</p></blockquote>
</blockquote>
]]></content:encoded>
			<wfw:commentRss>http://www.intelligrape.com/blog/2010/07/14/grails-unit-testing-for-beginners/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

