other register

Tuesday, June 29, 2010

mockLogging in Grails Test

"By calling mockLogging(Class) in your unit test, any subsequently create instance of the given class will magically gain a working log property that echoes all log messages to the console. By default, debug and trace messages aren't included, to avoid excess output, but you can enable the debug messages by passing true as an optional second argument to mockLogging()." -- (Grails in Action)

class JetService {
  def doSomthing() {
    def a = "hello world"
    log.debug a

class JetServiceUnitTests extends grails.test.GrailsUnitTestCase {
  void  testDoSomething() {
    mockLogging(JetService, true) // the second parameter "true" will output debug messages in the service method

When running the unit test:

grails test-app unit:unit JetServiceUnit

In the report, you can see the debug message is shown in the System.output

Wednesday, June 23, 2010

shouldFail in Groovy Testing

If the program hasn't got code to catch the runtime unchecked exceptions, then shouldFail can be used during groovy testing.

shouldFail() allows you to check that a particular lock of code throws an exception.

shouldFail (NullPointerException) {

However runtime unchecked exceptions can sometimes be considered as bugs in the programme and should be dealt with.

Monday, June 07, 2010

Grails Controller Unit Test

import grails.converters.JSON

class PersonController {
    def personService

    def jsonPeople = {
        def people = personService.getPerson('usrname', 'passwd')
        render people as JSON

class PersonService {

    static transactional = true

    def getPerson(String usrname, String password) {
        // some business logic
     return [firstname: 'joe', lastname: 'blog']

import grails.test.*
import grails.converters.JSON

class PersonControllerTests extends ControllerUnitTestCase {
protected void setUp() {

protected void tearDown() {

void testJsonResponse() {
controller.params.username= 'usrname'
controller.params.password = 'passwd'
                // mock the colloaborator
def personControl = mockFor(PersonService)
personControl.demand.getPerson(1..1) { String x, String y ->
                        // the number of parameters and return type have to match the method
return [firstname: 'joe', lastname: 'blog']
controller.personService = personControl.createMock()

//parse the JSON
def controllerResponse = controller.response.contentAsString
def jsonResult = JSON.parse(controllerResponse)

//navigate the JSON as an object
assertEquals 'joe', jsonResult.username
assertEquals 'blog', jsonResult.password