Test « Intelligrape Groovy & Grails Blogs

Archive for the ‘ Test ’ Category

Load Testing Made Easy with a Simple JMeter Utility

Posted by Vivek Krishna on November 30th, 2011

Load Testing is one of the major aspect which we all do for our applications, especially for those which have publicly available pages and has very heavy traffic. JMeter is a very commonly used tool for doing load testing. As developers, it is a very good tool to have in our skill set.

 

However we, as lazy productive developers are always trying to automate the processes so that we just need to configure it once and be able to run it from anywhere. Also added it to is the small matter of eliminating internet speed from the equation while load testing the pages. (Especially when we are concerned only with how the server responds to high loads). This means that we will be running the tests one of our remote servers which are closer to QA servers(or even the same machine!). We may also run schedule the tests to be run at night.

 

Himanshu and I modified some of the scripts he had written for one of the projects to make it more generic and generate Jmeter scripts and also a utility to run it for us and generate reports. The scripts(which run on *nix machines) are available here.

 

The steps to set it up are as follows

  1. Download Jmeter and install it at the location /opt/jmeter (The path to jmeter home would be /opt/jmeter)
  2. Install ant by doing (sudo apt-get install ant on Ubuntu)
  3. Clone/Fork the Git repository to your machine
  4. Add the ant-jmeter-<version>.jar file available at the Git Repo to /usr/share/ant/lib

The steps to configure and run the scripts are as follows

  1. Update conf.txt to suit your needs. It is a CSV file with the following parameters specified. URL,PORT,Path/?QueryParam=Value,TestName
  2. Update generate.groovy to configure parameters like number of threads, duration for the run, Test Name, Test Title etc
  3. Make generate.groovy and driver.sh executable (chmod +x generate.groovy driver.sh)
  4. Execute generate.groovy (./generate.groovy). This generates the required jmx files and updates the build.xml file
  5. Execute driver.sh (./driver.sh). This run the actual test
  6. The reports will be available under the target directory as TestName.html

The utility is very simple at the moment which caters only to simple get requests. In future, we would like to include Controllers, Config elements etc to be configurable, so that this utility can also be used for running Load Tests for secure pages.

 

We would be delighted to know what you would like to see in the future versions of this utility. :)

 

  • Share/Bookmark
Posted in Test

Grails productivity enhancer. The unsung hero ‘grails interactive mode’

Posted by Mohd Farid on November 30th, 2011

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.



Where should I use grails –interactive mode while developing in grails?
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.


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:

grails test-app unit: PersonUtilTests

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

 grails --interactive

This shall bring the grails infrastructure up and make it just ready to run commands. It takes around 5 seconds.

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):

Now, to test the app I can use the following command:

-------------------------------------------------------
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

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

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.

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.


Just in case you have not tried it. Please give it a shot. Believe me, it’s worth trying, you wont be disappointed!!!


Mohd Farid
farid@intelligrape.com

  • Share/Bookmark
Posted in Grails, Test, Unit Test

Initializations in Grails Unit Test Cases

Posted by Imran Mir on June 14th, 2011

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 id field,e.g., while testing a method of a class Student :

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<Student> findMySchoolsStudentsWithNamesLike(String nameLike) {
    List<Student> students = Student.findAllBySchoolAndNameLike(this.school, '%' + nameLike + '%')
    return students
  }

}

To test the method, a Spock test case with the simplified initializations will be like:

 def "My School students are retrieved correctly"() {
    setup:
    School school = new School(id: 1)
    List<Student> students = (1..10).collect {new Student(id: it, name: "name${it}", school: school)}
    mockDomain(Student, students)

    expect:
    students[0].findMySchoolsStudentsWithNamesLike('1').size() == 2
  }

Similar setup can work in Grail Unit test case.
Simplification of the initialization process has made Unit testing simpler and faster, thus allowing us to write more Unit test cases.

Cheers,
Imran Mir
imran@intelligrape.com

  • Share/Bookmark
Posted in Grails, Groovy, Test, Unit Test

Exception Testing using Spock in grails

Posted by Uday Pratap Singh on May 4th, 2011

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 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

String getUserType(int age){
    if(age<=0){
        throw new MyException("Invalid age")
    }else if( age>0 && age<50){
        return "Young"
    }else{
        return "Old"
    }
}

Now we will write the test case of this method for checking whether exception is thrown for invalid inputs or not.

def "exception should be thrown only for age less than or equal to 0"{
    given:
        String type = getUserType(34)
    expect:
        type == "Young"
        notThrown(MyException)
    when:
        type = getUserType(0)
    then:
        MyException me = thrown()
        me.message == "Invalid age"
}

This is how we have tested whether exception is thrown for invalid input or not.



Hope it helps


## Uday Pratap Singh ##
uday@intelligrape.com
http://www.IntelliGrape.com/
http://in.linkedin.com/in/meudaypratap

  • Share/Bookmark
Posted in Grails, Test, Unit Test

Interaction based testing using Spock in Grails

Posted by Uday Pratap Singh on April 7th, 2011

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.

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

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("Exception while sending email to user ${to}, Exception is ${t.getStackTrace()}")
    }
  }
}

and you have a method which calls this method

class UserService {

def emailService

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

  }

}

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

def "account activation mail sent to user"(){
setup:
UserService userService = new UserService()

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

User user = new User(email : "testUser@gmail")

when:
userService.sendActivationMail(user)

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

}

The then block ensures that the exactly 1 call is made to sendMail method with exactly the same arguments.
We can have other use cases for interaction based testing like making calls to external APIs, logging different statements in different conditions.



Hope it helps


## Uday Pratap Singh ##
uday@intelligrape.com
http://www.IntelliGrape.com/
http://in.linkedin.com/in/meudaypratap

  • Share/Bookmark
Posted in Grails, Test, Unit Test

Grails Unit test case for cookies

Posted by Uday Pratap Singh on March 3rd, 2011

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.

To do this I did the following in my unit test setup

Cookie cookie = new Cookie("APPNAME", "ABCD")
mockRequest.cookies = [cookie].toArray()

Now I can test my action easily :) .


Hope it helps


## Uday Pratap Singh ##
uday@intelligrape.com
http://www.IntelliGrape.com/
http://in.linkedin.com/in/meudaypratap

  • Share/Bookmark
Posted in Grails, Test, Unit Test

Testing custom validator in grails unit test case

Posted by Vishal Sahu on November 14th, 2010

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 “mockForConstraintsTests()” for validating constraints on Domain as well as Command-Object fields.

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.


I created custom validator for this which looks like.

 
  password(nullable: false, blank: false, minSize: 6)
  confirmPassword(nullable: false, blank: false, validator: {val, obj ->
            obj.properties['password'] == val
 })

The unit test which i write for this is like :-

void testUserPasswordConstraints() {
 
        mockForConstraintsTests(UserCommandObject)
        UserCommandObject uco = new UserCommandObject()
        uco.password="abcde"
        uco.confirmPassword="xyz"
        uco.validate()
        assertNotNull(uco.errors["confirmPassword"])  
// Validation message for password and confirmPassword field do not match
 
 }

So, by using ‘mockForConstraintsTests()’ 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.


Hope this helps.

Vishal Sahu
vishal@intelligrape.com
www.intelligrape.com

  • Share/Bookmark
Posted in Grails, Groovy, Test, Unit Test

Tips for Agile Development with Unit Testing approach.

Posted by Salil on July 14th, 2010

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’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.

Well, here are some tips which really helped me to achieve faster implementation and more stable application (esp. when working with third party APIs).

TRY TO MAKE YOUR CODE UNIT TESTABLE as much as possible.

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.

2. Try to make small chunks of code (in form of methods) with least dependency on external things.
Avoid Domain/Database/Environment specific code. In other words, don’t put any kind of framework specific dependency. In some cases you can’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.

3. In case you have some dependencies (and that can not be avoided) – Try to mock it up. In many cases it’s possible. If you are using Grails/Groovy kind of framework/language – you have an edge to take an advantage of meta-programming.

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 – invoke your API based service methods. And run it. Wow.. that’s it.

Advantages:
If there’s any kind of changes (from service provider), that can break your application’s functionality, test driven development will work as a “Life Saver”. It can tell you where’s the problem and why it happened. And you can make appropriate changes to stabilize it again.

Same thing implements when you develop a new feature. Unit Test Case helps you see the results in few seconds. Instead of waiting for 10-15 minutes (until application starts).

Isn’t it cool?

I really appreciate this approach. Hope others will also use it.

Thanks
Salil Kalia

  • Share/Bookmark
Posted in Grails, Groovy, Test, Unit Test

Grails unit testing for beginners

Posted by Imran Mir on July 14th, 2010

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 in a service ?

Ans: You would need to follow these simple steps:

Suppose you want to write a unit test case for a someFunction() in MyService:

class MyService {
    public String myFunction() {
      return "testString"
    }
  }

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

public void testMyFunction() {
    def myService = new MyService()
    String string = myService.myFunction()
    assertEquals "testString", string
  }

Ques: I am saving an object from this function. How can I test that ?

 public void myFunction(int number, String name) {
    MyDomainClass object = new MyDomainClass(age: number, name: name)
    object.save()
  }

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

   def instances = []
   def myTestDomain = mockDomain('MyDomainClass',instances)

instances 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.

 public void testMyFunction() {
    def instances = []
    def myTestDomain = mockDomain('MyDomainClass', instances)
    def myService = new MyService()
    String string = myService.myFunction(30, 'myName')
    assertEquals 1, instances.size()
  }

Ques: What does this mockDomain do ?

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.

Ques: That was great. But now my function uses some other service to do some job. How can I test that ?

  public void myFunction(String empId) {
    String name = otherService.someOtherFunction(empId)
    MyDomainClass object = new MyDomainClass(name: name)
    object.save()
  }

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

void testMyFunction() {
    def otherService = mockFor(OtherService)
    otherService.demand.someOtherFunction() {empId-&gt; return "testName"}
    def myService = new MyService()
    myService.otherService = otherService.createMock()
    String string = myService.myFunction(30, 'myName')
    assertEquals 1, instances.size()
}

Ques: What does this mockFor method do ?

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 demand 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.

 otherService.demand.someOtherFunction(1..2) {empId; return "testName"}

Here, it means someOtherFunction() will be called not more than 2 times in the function.

Hope this helps.
Imran Mir
imran@intelligrape.com

  • Share/Bookmark
Posted in Grails, Groovy, Test, Unit Test