Mocking a static method referencing a request object.

157 views
Skip to first unread message

olivier nguyen

unread,
Feb 1, 2013, 6:13:05 PM2/1/13
to spockfr...@googlegroups.com
Hi all,

I am writing a unit test for a service (ex: AddressService) that calls a static method from this helper class:

class AccountUtils {

    /* ... Some code ... */    

    static getUserLocale() {
        Locale locale = RequestContextUtils.getLocale(RequestContextHolder.requestAttributes.request)
String languageCode = locale.getLanguage()
supportedLanguagesSet.contains(languageCode) ? locale : Locale.ENGLISH
    }
}


Here is the message I get when running the test:

services.AddressService  - Cannot get property 'request' on null object

Anybody ever ran into this?

Thanks a lot,

-Olivier


Noam Tenne

unread,
Feb 2, 2013, 4:14:12 AM2/2/13
to spockfr...@googlegroups.com
Hi Olivier,

Can you show us how you prepare the different interactions and mocks?

Cheers,
Noam

olivier nguyen

unread,
Feb 7, 2013, 1:01:02 PM2/7/13
to spockfr...@googlegroups.com
Hi Noam, thank you for proposing your help.

I am pasting all the code ...

Thought: I think the error is due to the use of a static method in the AddressService's transform method.
I read that testing code using static method can be a sign of code smell and that it makes unit testing much more difficult that it should be.

Looking forward to your inputs! 

class AddressService {
def lookupService
def provinceService
def addressFormatHelper
def transform(acsAddress, country) {
def address = new Address()
try {
address.addressFormat = addressFormatHelper.getAddressFormat(country)
if (address) {
address.address1 = acsAddress.getAddress1()
/* other address fields */
address.country = lookupService.getCountry(acsAddress.getCountry(), AccountUtils.getUserLocale().getLanguage())
}
} catch (all) {
log.error "$all.message"
}
address
}
}


class AddressServiceSpec extends BaseUnitSpec {
def testTransform() {
setup:
def servletRequest = new MockHttpServletRequest()
service.lookupService = Mock(LookupService)
service.provinceService  = Mock(ProvinceService)
service.addressFormatHelper = Mock(AddressFormatHelper)
def utils = Mock(AccountUtils)
utils.getUserLocale() >> new Locale("en")
AcsAddress acsAddress = new AcsAddress()
acsAddress.address1 = "Street Addres 1"
/* other fields */
service.provinceService.find(_,_) >> Mock(Province)
service.lookupService.getCountry(_,_) >> "United States"
service.addressFormatHelper.getAddressFormat(_) >> Mock(AddressFormat)
when:
def address = service.transform (acsAddress, "US")
then:
address.address1 == acsAddress.address1
}
}


Reply all
Reply to author
Forward
0 new messages