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

[java]
protected PropertiesHolder getMergedProperties(final Locale locale){}
[/java]

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:

[java]
class CustomProperties {
Properties properties
}
[/java]

Mock getMergedProperties():

[java]
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
[/java]

Finally, our test case will look like

[java]
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’)
}
[/java]

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 Reply

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