I am Newbie to Java and Junit,
Does Anyone know how to write test cases for private functions in Junit ?
After Some research in Google I setup environment and wrote unit test cases for public functions and mocked parent classes with help of Mock() proxy.
For public function with inline valued arguments, I reached my expectations and tested both Positive and Negative Path.
For Private Methods I followed
How do I test a private function or a class that has private methods, fields or inner classes?
Method method = targetClass.getDeclaredMethod(methodName, argClasses);
method.setAccessible(true);
return method.invoke(targetObject, argObjects);
And for fields:
Field field = targetClass.getDeclaredField(fieldName);
field.setAccessible(true);
field.set(object, value);
code:
public class universalConfiguration {
private Integer getTotalDocuments(Client client, String indexName, String indexType, QueryBuilder searchQueryBuilder) {
SearchResponse response = client.prepareSearch()
.setIndices(indexName)
.setTypes(indexType)
.setSize(0)
.setQuery(searchQueryBuilder)
.execute().actionGet();
return (int) response.getHits().totalHits;
}
}
This is My code I want to test this private method with this public class, i tried to use this method using getDeclaredMethod and setAccessible but I am getting errors.
UniversalConfiguration universalConfiguration = new UniversalConfiguration();
getTotalDocuments getTotalDocuments= universalConfiguration .
getDeclaredMethod(getTotalDocuments,
client,
indexName,
indexType,
searchQueryBuilder);
getTotalDocuments.setAccessible(true);
getTotalDocuments method cannot be resolved to a type
Correct me If i did any mistakes.