Unit-Tests : Getting started with Service Unit Test

14 / Jun / 2010 by Imran Mir 1 comments

Hi all,

Here I am giving a brief introduction about unit testing of services in grails. I will explain it with the help of a simple example.

We have a domain class named: Item
Two services : UtilService and ItemService

Code of UtilService.groovy

// class UtilService code

class UtilService {
    boolean transactional = true
    Integer calculatePrice(Item item, Integer vat, Integer profit) {
        return item.price * vat * profit
    }
}

Code of ItemService.groovy

// ItemService class code

class ItemService {
    boolean transactional = true
    def utilService
    Integer calculateCost(Item item,Integer quantity) {
        Integer price = utilService.calculatePrice(item,5,8)
        Integer totalCost = price * quantity
        return totalCost
    }
}

Our test case:-

  void test_calculateCost() {
 // Step-1: Mocking the domain class
        def instance = [new Item()]
        mockDomain(Item, instance)

//Step-2: Mocking the service and its method used in the function that has to be tested
        def otherService = mockFor(UtilService)
        otherService.demand.calculatePrice(1) {l,m, n -> return 150}

// Step-3: creating the instance of our service
        def itemService = new ItemService()
        itemService.utilService = otherService.createMock()

// Step-4: Calling the method to be tested
        def amount = itemService.calculateCost(instance[0],10)

        assertEquals 1500, amount
    }

Hope it helps.
For more…. wait for the next blog on unit testing

Regards
Imran
imran@intelligrape.com

FOUND THIS USEFUL? SHARE IT

comments (1 “Unit-Tests : Getting started with Service Unit Test”)

Leave a Reply

Your email address will not be published. Required fields are marked *