Unit test a method returning an object of protected class

22 / Mar / 2015 by Neha Gupta 0 comments

Following is an example of testing a method which returns an object of protect class:

In the previous blog we talked about fetching the list of message codes from message.properties file.

While writing the test case for CustomisedPluginAwareResourceBundleMessageSource, I was not able to test the message properties that are available when your application is actually running. Functionality rendered by getMergedProperties() method of ReloadableResourceBundleMessageSource.java is not available while writing test cases.

Signature for getMergedProperties() is

protected PropertiesHolder getMergedProperties(final Locale locale){}

Also the class PropertiesHolder is protected so we cant access it in our test files.

Here is a proposed solution for testing listMessageCodes(). Create a class like CustomProperties which is similar to PropertiesHolder in behaviour:

class CustomProperties {
    Properties properties
}

Mock getMergedProperties():

messageSource.metaClass.getMergedProperties = { final Locale tempLocale ->
            Properties properties = new Properties()
            properties.setProperty('square.black.label', 'Black Square')
            properties.setProperty('circle.violet.label', 'Violet Circle')
            properties.setProperty('fruit.black.label', 'Black Grape')

            CustomProperties customProperties = new CustomProperties()
            customProperties.properties = properties
            return customProperties
        }

//messageSource referred here is
//   CustomisedPluginAwareResourceBundleMessageSource messageSource

Finally, our test case will look like

void "test listMessageCodes"() {
        setup:
        Locale locale = new Locale('en', 'US')
        String lookupMessageCode = 'black'
        messageSource.metaClass.getMergedProperties = { final Locale tempLocale ->
            Properties properties = new Properties()
            properties.setProperty('square.black.label', 'Black Square')
            properties.setProperty('circle.violet.label', 'Violet Circle')
            properties.setProperty('fruit.black.label', 'Black Grape')

            CustomProperties customProperties = new CustomProperties()
            customProperties.properties = properties
            return customProperties
        }

        when:
        List list = messageSource.listMessageCodes(locale, lookupMessageCode)

        then:
        list.get(0).toString().contains('black')
    }

Don’t forget to add @ConfineMetaClassChanges to the spec. It restores the meta classes to its previous state.

That’s it…

Search for a demo here.

FOUND THIS USEFUL? SHARE IT

Leave a comment -