---
title: "How to test a class that has private methods, fields or inner classes"  
description: "How to test a class that has private methods, fields or inner classes"  
author: "Anonymous User"  
published: 2015-05-06  
updated: 2015-05-06  
canonical: https://www.mindstick.com/forum/23191/how-to-test-a-class-that-has-private-methods-fields-or-inner-classes  
category: "java"  
tags: ["java", "unit testing"]  
reading_time: 1 minute  

---

# How to test a class that has private methods, fields or inner classes

How do I use JUnit to [test](https://yourviews.mindstick.com/story/1427/explosive-facts-about-trinity-test-world-s-first-nuclear-bomb) a [class](https://www.mindstick.com/blog/165/generic-class-in-c-sharp) that has [internal](https://www.mindstick.com/interview/773/describe-the-accessibility-modifier-protected-internal) [private methods](https://www.mindstick.com/forum/159219/how-can-i-test-a-class-that-has-private-methods-fields-or-inner-classes), [fields](https://www.mindstick.com/forum/159126/sql-query-for-all-tables-and-fields-in-an-oracle-db) or [nested](https://www.mindstick.com/forum/45/itemcommand-event-in-nested-repeater-and-listview) classes? It seems bad to change the [access](https://www.mindstick.com/articles/12994/how-foreigners-can-access-blocked-websites-in-china) modifier for a [method](https://www.mindstick.com/forum/166/webservice-method) just to be able to run a test.

## Replies

### Reply by Anonymous User

If you have somewhat of a legacy application, and you're not allowed to change the visibility of your [methods](https://www.mindstick.com/articles/13060/runny-nose-remedy-methods-that-work-best), the best way to test [private](https://www.mindstick.com/blog/11097/java-access-modifiers-the-public-and-the-private-modifiers) methods is to use [reflection](http://en.wikipedia.org/wiki/Reflection_%28computer_programming%29).\
Internally we're using helpers to get/set private and private static variables as well as invoke private and private static methods. The following patterns will let you do pretty much anything related to the private methods and fields. Of course you can't change private static final variables through reflection.\

```
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);
```

**Notes:**1. targetClass.getDeclaredMethod(methodName, argClasses) lets you look into private methods. The same thing applies for getDeclaredField.2. The setAccessible(true) is required to play around with privates.


---

Original Source: https://www.mindstick.com/forum/23191/how-to-test-a-class-that-has-private-methods-fields-or-inner-classes

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
