<p>How do I use JUnit to test a class that has internal private methods, fields or nested classes?</p>
<p>It seems bad to change the access modifier for a method just to be able to run a test.</p>

[{'answer_id': 34586, 'author': 'Sir Rippov the Maple', 'author_id': 2822, 'author_profile': 'https://Stackoverflow.com/users/2822', 'pm_score': 10, 'selected': False, 'text': '<p>The best way to test a private method is via another public method. If this cannot be done, then one of the following conditions is true:</p>\n\n<ol>\n<li>The private method is dead code</li>\n<li>There is a design smell near the class that you are testing</li>\n<li>The method that you are trying to test should not be private</li>\n</ol>\n'}, {'answer_id': 34590, 'author': 'John Channing', 'author_id': 3305, 'author_profile': 'https://Stackoverflow.com/users/3305', 'pm_score': 7, 'selected': False, 'text': '<p>Generally a unit test is intended to exercise the public interface of a class or unit. Therefore, private methods are implementation detail that you would not expect to test explicitly.</p>\n'}, {'answer_id': 34594, 'author': 'Thomas Owens', 'author_id': 572, 'author_profile': 'https://Stackoverflow.com/users/572', 'pm_score': 6, 'selected': False, 'text': '<p>The private methods are called by a public method, so the inputs to your public methods should also test private methods that are called by those public methods. When a public method fails, then that could be a failure in the private method.</p>\n'}, {'answer_id': 34598, 'author': 'Iker Jimenez', 'author_id': 2697, 'author_profile': 'https://Stackoverflow.com/users/2697', 'pm_score': 8, 'selected': False, 'text': '<p>From this article: <a href="http://www.artima.com/suiterunner/private.html" rel="noreferrer">Testing Private Methods with JUnit and SuiteRunner</a> (Bill Venners), you basically have 4 options:</p>\n<blockquote>\n<ol>\n<li>Don\'t test private methods.</li>\n<li>Give the methods package access.</li>\n<li>Use a nested test class.</li>\n<li>Use reflection.</li>\n</ol>\n</blockquote>\n'}, {'answer_id': 34630, 'author': 'bmurphy1976', 'author_id': 1931, 'author_profile': 'https://Stackoverflow.com/users/1931', 'pm_score': 4, 'selected': False, 'text': '<p>I tend not to test private methods.  There lies madness.  Personally, I believe you should only test your publicly exposed interfaces (and that includes protected and internal methods).  </p>\n'}, {'answer_id': 34644, 'author': 'Josh Brown', 'author_id': 2030, 'author_profile': 'https://Stackoverflow.com/users/2030', 'pm_score': 3, 'selected': False, 'text': '<p>For Java I\'d use <a href="http://docs.oracle.com/javase/tutorial/reflect/index.html" rel="nofollow noreferrer">reflection</a>, since I don\'t like the idea of changing the access to a package on the declared method just for the sake of testing. However, I usually just test the public methods which should also ensure the private methods are working correctly.</p>\n\n<blockquote>\n  <p>you can\'t use reflection to get private methods from outside the owner class, the private modifier affects reflection also</p>\n</blockquote>\n\n<p>This is not true. You most certainly can, as mentioned in <a href="https://stackoverflow.com/questions/34571/whats-the-best-way-of-unit-testing-private-methods#34658">Cem Catikkas\'s answer</a>.</p>\n'}, {'answer_id': 34658, 'author': 'Cem Catikkas', 'author_id': 3087, 'author_profile': 'https://Stackoverflow.com/users/3087', 'pm_score': 12, 'selected': True, 'text': '<p>If you have somewhat of a legacy <strong>Java</strong> application, and you\'re not allowed to change the visibility of your methods, the best way to test private methods is to use <a href="http://en.wikipedia.org/wiki/Reflection_%28computer_programming%29" rel="noreferrer">reflection</a>.</p>\n<p>Internally we\'re using helpers to get/set <code>private</code> and <code>private static</code> variables as well as invoke <code>private</code> and <code>private static</code> methods. The following patterns will let you do pretty much anything related to the private methods and fields. Of course, you can\'t change <code>private static final</code> variables through reflection.</p>\n<pre><code>Method method = TargetClass.getDeclaredMethod(methodName, argClasses);\nmethod.setAccessible(true);\nreturn method.invoke(targetObject, argObjects);\n</code></pre>\n<p>And for fields:</p>\n<pre><code>Field field = TargetClass.getDeclaredField(fieldName);\nfield.setAccessible(true);\nfield.set(object, value);\n</code></pre>\n<hr />\n<blockquote>\n<p><strong>Notes:</strong></p>\n<ol>\n<li><code>TargetClass.getDeclaredMethod(methodName, argClasses)</code> lets you look into <code>private</code> methods. The same thing applies for\n<code>getDeclaredField</code>.</li>\n<li>The <code>setAccessible(true)</code> is required to play around with privates.</li>\n</ol>\n</blockquote>\n'}, {'answer_id': 38425, 'author': 'Grundlefleck', 'author_id': 4120, 'author_profile': 'https://Stackoverflow.com/users/4120', 'pm_score': 5, 'selected': False, 'text': '<p>Having tried Cem Catikkas\' <a href="https://stackoverflow.com/questions/34571/whats-the-best-way-of-unit-testing-private-methods#34658">solution using reflection</a> for Java, I\'d have to say his was a more elegant solution than I have described here. However, if you\'re looking for an alternative to using reflection, and have access to the source you\'re testing, this will still be an option.</p>\n\n<p>There is possible merit in testing private methods of a class, particularly with <a href="http://en.wikipedia.org/wiki/Test-driven_development" rel="noreferrer">test-driven development</a>, where you would like to design small tests before you write any code.</p>\n\n<p>Creating a test with access to private members and methods can test areas of code which are difficult to target specifically with access only to public methods. If a public method has several steps involved, it can consist of several private methods, which can then be tested individually.</p>\n\n<p>Advantages:</p>\n\n<ul>\n<li>Can test to a finer granularity</li>\n</ul>\n\n<p>Disadvantages:</p>\n\n<ul>\n<li>Test code must reside in the same\nfile as source code, which can be\nmore difficult to maintain</li>\n<li>Similarly with .class output files, they must remain within the same package as declared in source code</li>\n</ul>\n\n<p>However, if continuous testing requires this method, it may be a signal that the private methods should be extracted, which could be tested in the traditional, public way.</p>\n\n<p>Here is a convoluted example of how this would work:</p>\n\n<pre><code>// Import statements and package declarations\n\npublic class ClassToTest\n{\n    private int decrement(int toDecrement) {\n        toDecrement--;\n        return toDecrement;\n    }\n\n    // Constructor and the rest of the class\n\n    public static class StaticInnerTest extends TestCase\n    {\n        public StaticInnerTest(){\n            super();\n        }\n\n        public void testDecrement(){\n            int number = 10;\n            ClassToTest toTest= new ClassToTest();\n            int decremented = toTest.decrement(number);\n            assertEquals(9, decremented);\n        }\n\n        public static void main(String[] args) {\n            junit.textui.TestRunner.run(StaticInnerTest.class);\n        }\n    }\n}\n</code></pre>\n\n<p>The inner class would be compiled to <code>ClassToTest$StaticInnerTest</code>.</p>\n\n<p>See also: <em><a href="http://www.javaworld.com/javaworld/javatips/jw-javatip106.html" rel="noreferrer">Java Tip 106: Static inner classes for fun and profit</a></em></p>\n'}, {'answer_id': 46255, 'author': 'Don Kirkby', 'author_id': 4794, 'author_profile': 'https://Stackoverflow.com/users/4794', 'pm_score': 5, 'selected': False, 'text': "<p>If you're trying to test existing code that you're reluctant or unable to change, reflection is a good choice.</p>\n\n<p>If the class's design is still flexible, and you've got a complicated private method that you'd like to test separately, I suggest you pull it out into a separate class and test that class separately. This doesn't have to change the public interface of the original class; it can internally create an instance of the helper class and call the helper method.</p>\n\n<p>If you want to test difficult error conditions coming from the helper method, you can go a step further. Extract an interface from the helper class, add a public getter and setter to the original class to inject the helper class (used through its interface), and then inject a mock version of the helper class into the original class to test how the original class responds to exceptions from the helper. This approach is also helpful if you want to test the original class without also testing the helper class.</p>\n"}, {'answer_id': 51192, 'author': 'Will Sargent', 'author_id': 5266, 'author_profile': 'https://Stackoverflow.com/users/5266', 'pm_score': 4, 'selected': False, 'text': '<p>If you want to test private methods of a legacy application where you can\'t change the code, one option for Java is <a href="http://code.google.com/p/jmockit/" rel="noreferrer">jMockit</a>, which will allow you to create mocks to an object even when they\'re private to the class.</p>\n'}, {'answer_id': 52054, 'author': 'Jay Bazuzi', 'author_id': 5314, 'author_profile': 'https://Stackoverflow.com/users/5314', 'pm_score': 9, 'selected': False, 'text': "<p>When I have private methods in a class that are sufficiently complicated that I feel the need to test the private methods directly, that is a code smell: my class is too complicated.  </p>\n\n<p>My usual approach to addressing such issues is to tease out a new class that contains the interesting bits.  Often, this method and the fields it interacts with, and maybe another method or two can be extracted in to a new class.  </p>\n\n<p>The new class exposes these methods as 'public', so they're accessible for unit testing.  The new and old classes are now both simpler than the original class, which is great for me (I need to keep things simple, or I get lost!).</p>\n\n<p>Note that I'm not suggesting that people create classes without using their brain! The point here is to use the forces of unit testing to help you find good new classes.  </p>\n"}, {'answer_id': 53571, 'author': 'Darren Greaves', 'author_id': 151, 'author_profile': 'https://Stackoverflow.com/users/151', 'pm_score': 4, 'selected': False, 'text': '<p>As many above have suggested, a good way is to test them via your public interfaces.</p>\n<p>If you do this, it\'s a good idea to use a <a href="https://en.wikipedia.org/wiki/Code_coverage" rel="nofollow noreferrer">code coverage</a> tool (like <a href="https://en.wikipedia.org/wiki/Java_code_coverage_tools#EMMA" rel="nofollow noreferrer">EMMA</a>) to see if your private methods are in fact being executed from your tests.</p>\n'}, {'answer_id': 57795, 'author': 'Joe', 'author_id': 5313, 'author_profile': 'https://Stackoverflow.com/users/5313', 'pm_score': 4, 'selected': False, 'text': '<p>If you\'re using JUnit, have a look at <a href="http://junit-addons.sourceforge.net/" rel="noreferrer">junit-addons</a>. It has the ability to ignore the Java security model and access private methods and attributes.</p>\n'}, {'answer_id': 91206, 'author': 'Aaron', 'author_id': 14153, 'author_profile': 'https://Stackoverflow.com/users/14153', 'pm_score': 4, 'selected': False, 'text': '<p>First, I\'ll throw this question out: Why do your private members need isolated testing? Are they that complex, providing such complicated behaviors as to require testing apart from the public surface? It\'s unit testing, not \'line-of-code\' testing. Don\'t sweat the small stuff.</p>\n<p>If they are that big, big enough that these private members are each a \'unit\' large in complexity—consider refactoring such private members out of this class.</p>\n<p>If refactoring is inappropriate or infeasible, can you use the <a href="https://en.wikipedia.org/wiki/Strategy_pattern" rel="nofollow noreferrer">strategy pattern</a> to replace access to these private member functions / member classes when under unit test? Under unit test, the strategy would provide added validation, but in release builds it would be simple passthrough.</p>\n'}, {'answer_id': 190338, 'author': 'ema', 'author_id': 19520, 'author_profile': 'https://Stackoverflow.com/users/19520', 'pm_score': 5, 'selected': False, 'text': "<p>Testing private methods breaks the encapsulation of your class because every time you change the internal implementation you break client code (in this case, the tests).</p>\n\n<p>So don't test private methods.</p>\n"}, {'answer_id': 549551, 'author': 'TofuBeer', 'author_id': 65868, 'author_profile': 'https://Stackoverflow.com/users/65868', 'pm_score': 5, 'selected': False, 'text': '<p>As others have said... don\'t test private methods directly. Here are a few thoughts:</p>\n<ol>\n<li>Keep all methods small and focused (easy to test, easy to find what is wrong)</li>\n<li>Use code coverage tools. I like <a href="http://cobertura.sourceforge.net/index.html" rel="nofollow noreferrer">Cobertura</a> (oh happy day, it looks like a new version is out!)</li>\n</ol>\n<p>Run the code coverage on the unit tests. If you see that methods are not fully tested add to the tests to get the coverage up. Aim for 100% code coverage, but realize that you probably won\'t get it.</p>\n'}, {'answer_id': 549558, 'author': 'TofuBeer', 'author_id': 65868, 'author_profile': 'https://Stackoverflow.com/users/65868', 'pm_score': 3, 'selected': False, 'text': '<p>You can turn off Java access restrictions for reflection so that private means nothing.</p>\n\n<p>The <code>setAccessible(true)</code> call does that.</p>\n\n<p>The only restriction is that a ClassLoader may disallow you from doing that.</p>\n\n<p>See <em><a href="http://www.onjava.com/pub/a/onjava/2003/11/12/reflection.html" rel="nofollow noreferrer">Subverting Java Access Protection for Unit Testing</a></em> (Ross Burton) for a way to do this in Java.</p>\n'}, {'answer_id': 549592, 'author': 'Thomas Hansen', 'author_id': 29746, 'author_profile': 'https://Stackoverflow.com/users/29746', 'pm_score': 2, 'selected': False, 'text': "<p>In C# you could have used <code>System.Reflection</code>, though in Java I don't know. If you &quot;feel you need to unit test private methods&quot;, my guess is that there is something else which is wrong...</p>\n<p>I would seriously consider looking at my architecture again with fresh eyes...</p>\n"}, {'answer_id': 1038507, 'author': 'Diego Amicabile', 'author_id': 126875, 'author_profile': 'https://Stackoverflow.com/users/126875', 'pm_score': 2, 'selected': False, 'text': '<p>What if your test classes are in the same package as the class that should be tested?</p>\n\n<p>But in a different directory of course, <code>src</code> &amp; <code>classes</code> for your source code, <code>test/src</code> and <code>test/classes</code> for your test classes. And let <code>classes</code> and <code>test/classes</code> be in your classpath.</p>\n'}, {'answer_id': 1043013, 'author': 'Jon', 'author_id': 128285, 'author_profile': 'https://Stackoverflow.com/users/128285', 'pm_score': 8, 'selected': False, 'text': '<p>I have used <a href="http://en.wikipedia.org/wiki/Reflection_%28computer_programming%29" rel="nofollow noreferrer">reflection</a> to do this for Java in the past, and in my opinion it was a big mistake.</p>\n<p>Strictly speaking, you should <em>not</em> be writing unit tests that directly test private methods. What you <em>should</em> be testing is the public contract that the class has with other objects; you should never directly test an object\'s internals. If another developer wants to make a small internal change to the class, which doesn\'t affect the classes public contract, he/she then has to modify your reflection based test to ensure that it works. If you do this repeatedly throughout a project, unit tests then stop being a useful measurement of code health, and start to become a hindrance to development, and an annoyance to the development team.</p>\n<p>What I recommend doing instead is using a code coverage tool, such as <a href="https://en.wikipedia.org/wiki/Java_code_coverage_tools#Cobertura" rel="nofollow noreferrer">Cobertura</a>, to ensure that the unit tests you write provide decent coverage of the code in private methods. That way, you indirectly test what the private methods are doing, and maintain a higher level of agility.</p>\n'}, {'answer_id': 3177465, 'author': 'Richard Le Mesurier', 'author_id': 383414, 'author_profile': 'https://Stackoverflow.com/users/383414', 'pm_score': 6, 'selected': False, 'text': "<p>Just two examples of where I would want to test a private method:</p>\n<ol>\n<li><p><strong>Decryption routines</strong> - I would not\nwant to make them visible to anyone to see just for\nthe sake of testing, else anyone can\nuse them to decrypt. But they are\nintrinsic to the code, complicated,\nand need to always work (the obvious exception is reflection which can be used to view even private methods in most cases, when <code>SecurityManager</code> is not configured to prevent this).</p>\n</li>\n<li><p><strong>Creating an SDK</strong> for community\nconsumption. Here public takes on a\nwholly different meaning, since this\nis code that the whole world may see\n(not just internal to my application). I put\ncode into private methods if I don't\nwant the SDK users to see it - I\ndon't see this as code smell, merely\nas how SDK programming works. But of\ncourse I still need to test my\nprivate methods, and they are where\nthe functionality of my SDK actually\nlives.</p>\n</li>\n</ol>\n<p>I understand the idea of only testing the &quot;contract&quot;. But I don't see one can advocate actually not testing code—your mileage may vary.</p>\n<p>So my trade-off involves complicating the JUnit tests with reflection, rather than compromising my security and SDK.</p>\n"}, {'answer_id': 4667692, 'author': 'phareim', 'author_id': 373975, 'author_profile': 'https://Stackoverflow.com/users/373975', 'pm_score': 5, 'selected': False, 'text': "<p>To test legacy code with large and quirky classes, it is often very helpful to be able to test the one private (or public) method I'm writing <em>right now</em>.</p>\n<p>I use the <strong>junitx.util.PrivateAccessor</strong>-package for Java. It has lots of helpful one-liners for accessing private methods and private fields.</p>\n<pre><code>import junitx.util.PrivateAccessor;\n\nPrivateAccessor.setField(myObjectReference, &quot;myCrucialButHardToReachPrivateField&quot;, myNewValue);\nPrivateAccessor.invoke(myObjectReference, &quot;privateMethodName&quot;, java.lang.Class[] parameterTypes, java.lang.Object[] args);\n</code></pre>\n"}, {'answer_id': 5083041, 'author': 'simpatico', 'author_id': 300248, 'author_profile': 'https://Stackoverflow.com/users/300248', 'pm_score': 4, 'selected': False, 'text': '<p>The answer from <a href="http://junit.org/faq.html#atests_11" rel="nofollow noreferrer">JUnit.org FAQ page</a>:</p>\n<blockquote>\n<p>But if you must...</p>\n<p>If you are using JDK 1.3 or higher, you can use reflection to subvert\nthe access control mechanism with the aid of the <a href="http://sourceforge.net/projects/privaccessor/" rel="nofollow noreferrer">PrivilegedAccessor</a>.\nFor details on how to use it, read <a href="http://www.onjava.com/pub/a/onjava/2003/11/12/reflection.html" rel="nofollow noreferrer">this article</a>.</p>\n<p>If you are using JDK 1.6 or higher and you annotate your tests with\n@Test, you can use <a href="http://dp4j.com" rel="nofollow noreferrer">Dp4j</a> to inject reflection in your test methods. For\ndetails on how to use it, see <a href="http://dp4j.com/testscript" rel="nofollow noreferrer">this test script</a>.</p>\n</blockquote>\n<p>P.S. I\'m the main contributor to <a href="http://dp4j.com" rel="nofollow noreferrer">Dp4j</a>. Ask <a href="https://stackoverflow.com/users/300248">me</a> if you need help. :)</p>\n'}, {'answer_id': 5820700, 'author': 'Gimby', 'author_id': 424903, 'author_profile': 'https://Stackoverflow.com/users/424903', 'pm_score': 0, 'selected': False, 'text': '<p>I only test the public interface, but I have been known to make specific private methods protected so I can either mock them out entirely, or add in additional steps specific for unit testing purposes. A general case is to hook in flags I can set from the unit test to make certain methods intentionally cause an exception to be able to test fault paths; the exception triggering code is only in the test path in an overridden implementation of the protected method.</p>\n\n<p>I minimize the need for this though and I always document the precise reasons to avoid confusion.</p>\n'}, {'answer_id': 8139572, 'author': 'marc wellman', 'author_id': 946904, 'author_profile': 'https://Stackoverflow.com/users/946904', 'pm_score': 2, 'selected': False, 'text': "<p>I am not sure whether this is a good technique, but I developed the following pattern to unit test private methods:</p>\n<p>I don't modify the visibility of the method that I want to test and add an additional method. Instead I am adding an additional public method for every private method I want to test. I call this additional method <code>Test-Port</code> and denote them with the prefix <code>t_</code>. This <code>Test-Port</code> method then simply accesses the according private method.</p>\n<p>Additionally, I add a Boolean flag to the <code>Test-Port</code> method to decide whether I grant access to the private method through the <code>Test-Port</code> method from outside. This flag is then set globally in a static class where I place e.g. other global settings for the application. So I can switch the access to the private methods on and off in one place, e.g., in the corresponding unit test.</p>\n"}, {'answer_id': 8704898, 'author': 'sagehen03', 'author_id': 107852, 'author_profile': 'https://Stackoverflow.com/users/107852', 'pm_score': 0, 'selected': False, 'text': '<p>Groovy has a <a href="http://jira.codehaus.org/browse/GROOVY-1875" rel="nofollow">bug/feature</a>, through which you can invoke private methods as if they were public.  So if you\'re able to use Groovy in your project, it\'s an option you can use in lieu of reflection.  Check out <a href="http://marciogarcia.com/?p=80" rel="nofollow">this page</a> for an example.</p>\n'}, {'answer_id': 15192546, 'author': 'Steven Bluen', 'author_id': 419109, 'author_profile': 'https://Stackoverflow.com/users/419109', 'pm_score': 1, 'selected': False, 'text': '<p><a href="https://en.wikipedia.org/wiki/Java_Modeling_Language" rel="nofollow noreferrer">JML</a> has a <em>spec_public</em> comment annotation syntax that allows you to specify a method as public during tests:</p>\n<pre><code>private /*@ spec_public @*/ int methodName(){\n...\n}\n</code></pre>\n<p>This syntax is discussed at <em><a href="http://www.eecs.ucf.edu/%7Eleavens/JML/jmlrefman/jmlrefman_2.html#SEC12" rel="nofollow noreferrer">2.4 Privacy Modifiers and Visibility</a></em>. There also exists a program that translates JML specifications into JUnit tests. I\'m not sure how well that works or what its capabilities are, but it doesn\'t appear to be necessary since JML is a viable testing framework on its own.</p>\n'}, {'answer_id': 18859235, 'author': 'Snicolas', 'author_id': 693752, 'author_profile': 'https://Stackoverflow.com/users/693752', 'pm_score': 4, 'selected': False, 'text': '<p>Today, I pushed a Java library to help testing private methods and fields. It has been designed with Android in mind, but it can really be used for any Java project.</p>\n<p>If you got some code with private methods or fields or constructors, you can use <a href="https://github.com/stephanenicolas/boundbox" rel="nofollow noreferrer"><strong>BoundBox</strong></a>. It does exactly what you are looking for.\nHere below is an example of a test that accesses two private fields of an Android activity to test it:</p>\n<pre><code>@UiThreadTest\npublic void testCompute() {\n\n    // Given\n    boundBoxOfMainActivity = new BoundBoxOfMainActivity(getActivity());\n\n    // When\n    boundBoxOfMainActivity.boundBox_getButtonMain().performClick();\n\n    // Then\n    assertEquals(&quot;42&quot;, boundBoxOfMainActivity.boundBox_getTextViewMain().getText());\n}\n</code></pre>\n<p><strong>BoundBox</strong> makes it easy to test private/protected fields, methods and constructors. You can even access stuff that is hidden by inheritance. Indeed, BoundBox breaks encapsulation. It will give you access to all that through reflection, <em><strong>but</strong></em> everything is checked at compile time.</p>\n<p>It is ideal for testing some legacy code. Use it carefully. ;)</p>\n'}, {'answer_id': 20337937, 'author': 'Antony Booth', 'author_id': 312957, 'author_profile': 'https://Stackoverflow.com/users/312957', 'pm_score': 5, 'selected': False, 'text': "<p>Private methods are consumed by public ones. Otherwise, they're dead code. That's why you test the public method, asserting the expected results of the public method and thereby, the private methods it consumes.</p>\n\n<p>Testing private methods should be tested by debugging before running your unit tests on public methods.</p>\n\n<p>They may also be debugged using test-driven development, debugging your unit tests until all your assertions are met.</p>\n\n<p>I personally believe it is better to create classes using TDD; creating the public method stubs, then generating unit tests with <strong>all</strong> the assertions defined in advance, so the expected outcome of the method is determined before you code it. This way, you don't go down the wrong path of making the unit test assertions fit the results. Your class is then robust and meets requirements when all your unit tests pass.</p>\n"}, {'answer_id': 20990300, 'author': 'Yuli Reiri', 'author_id': 1789360, 'author_profile': 'https://Stackoverflow.com/users/1789360', 'pm_score': 4, 'selected': False, 'text': '<p>Here is my generic function to test private fields:</p>\n\n<pre><code>protected &lt;F&gt; F getPrivateField(String fieldName, Object obj)\n    throws NoSuchFieldException, IllegalAccessException {\n    Field field =\n        obj.getClass().getDeclaredField(fieldName);\n\n    field.setAccessible(true);\n    return (F)field.get(obj);\n}\n</code></pre>\n'}, {'answer_id': 23441118, 'author': 'loknath', 'author_id': 2373304, 'author_profile': 'https://Stackoverflow.com/users/2373304', 'pm_score': 4, 'selected': False, 'text': '<p>A private method is only to be accessed within the same class. So there is no way to test a “private” method of a target class from any test class. A way out is that you can perform unit testing manually or can change your method from “private” to “protected”.</p>\n\n<p>And then a protected method can only be accessed within the same package where the class is defined. So, testing a protected method of a target class means we need to define your test class in the same package as the target class.</p>\n\n<p>If all the above does not suits your requirement, use <a href="https://stackoverflow.com/questions/11483647/how-to-access-private-methods-and-private-data-members-via-reflection"><strong>the  reflection way</strong></a> to access the private method.  </p>\n'}, {'answer_id': 26855013, 'author': 'Steve Chambers', 'author_id': 1063716, 'author_profile': 'https://Stackoverflow.com/users/1063716', 'pm_score': 5, 'selected': False, 'text': '<p>If using Spring, <a href="http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/test/util/ReflectionTestUtils.html" rel="noreferrer">ReflectionTestUtils</a> provides some handy tools that help out here with minimal effort. For example, to set up a mock on a private member without being forced to add an undesirable public setter:</p>\n\n<pre><code>ReflectionTestUtils.setField(theClass, "theUnsettableField", theMockObject);\n</code></pre>\n'}, {'answer_id': 30093076, 'author': 'CoronA', 'author_id': 4497253, 'author_profile': 'https://Stackoverflow.com/users/4497253', 'pm_score': 3, 'selected': False, 'text': '<p>I recently had this problem and wrote a little tool, called <a href="https://github.com/almondtools/picklock" rel="noreferrer">Picklock</a>, that avoids the problems of explicitly using the Java reflection API, two examples:</p>\n\n<p><strong>Calling methods, e.g. <code>private void method(String s)</code> - by Java reflection</strong></p>\n\n<pre><code>Method method = targetClass.getDeclaredMethod("method", String.class);\nmethod.setAccessible(true);\nreturn method.invoke(targetObject, "mystring");\n</code></pre>\n\n<p><strong>Calling methods, e.g. <code>private void method(String s)</code> - by Picklock</strong></p>\n\n<pre><code>interface Accessible {\n  void method(String s);\n}\n\n...\nAccessible a = ObjectAccess.unlock(targetObject).features(Accessible.class);\na.method("mystring");\n</code></pre>\n\n<p><strong>Setting fields, e.g. <code>private BigInteger amount;</code> - by Java reflection</strong></p>\n\n<pre><code>Field field = targetClass.getDeclaredField("amount");\nfield.setAccessible(true);\nfield.set(object, BigInteger.valueOf(42));\n</code></pre>\n\n<p><strong>Setting fields, e.g. <code>private BigInteger amount;</code> - by Picklock</strong></p>\n\n<pre><code>interface Accessible {\n  void setAmount(BigInteger amount);\n}\n\n...\nAccessible a = ObjectAccess.unlock(targetObject).features(Accessible.class);\na.setAmount(BigInteger.valueOf(42));\n</code></pre>\n'}, {'answer_id': 31020978, 'author': 'Mikhail', 'author_id': 1781357, 'author_profile': 'https://Stackoverflow.com/users/1781357', 'pm_score': 6, 'selected': False, 'text': '<p>In the <a href="http://en.wikipedia.org/wiki/Spring_Framework" rel="noreferrer">Spring Framework</a> you can test private methods using this method:</p>\n\n<pre><code>ReflectionTestUtils.invokeMethod()\n</code></pre>\n\n<p>For example:</p>\n\n<pre><code>ReflectionTestUtils.invokeMethod(TestClazz, "createTest", "input data");\n</code></pre>\n'}, {'answer_id': 36115967, 'author': 'supernova', 'author_id': 538160, 'author_profile': 'https://Stackoverflow.com/users/538160', 'pm_score': 6, 'selected': False, 'text': '<p>Another approach I have used is to change a private method to package private or protected then complement it with the <strong>@VisibleForTesting</strong> annotation of the Google Guava library.</p>\n\n<p>This will tell anybody using this method to take caution and not access it directly even in a package. Also a test class need not be in same package <strong>physically</strong>, but in the same package under the <strong>test</strong> folder.</p>\n\n<p>For example, if a method to be tested is in <code>src/main/java/mypackage/MyClass.java</code> then your test call should be placed in <code>src/test/java/mypackage/MyClassTest.java</code>. That way, you got access to the test method in your test class.</p>\n'}, {'answer_id': 37591098, 'author': 'Olcay Tarazan', 'author_id': 2335016, 'author_profile': 'https://Stackoverflow.com/users/2335016', 'pm_score': 4, 'selected': False, 'text': '<p>Please see below for an example;</p>\n\n<p>The following import statement should be added:</p>\n\n<pre><code>import org.powermock.reflect.Whitebox;\n</code></pre>\n\n<p>Now you can directly pass the object which has the private method, method name to be called, and additional parameters as below.</p>\n\n<pre><code>Whitebox.invokeMethod(obj, "privateMethod", "param1");\n</code></pre>\n'}, {'answer_id': 37618628, 'author': 'Legna', 'author_id': 2197088, 'author_profile': 'https://Stackoverflow.com/users/2197088', 'pm_score': 2, 'selected': False, 'text': '<p>A quick addition to <a href="https://stackoverflow.com/questions/34571/how-do-i-test-a-class-that-has-private-methods-fields-or-inner-classes#34658">Cem Catikka\'s answer</a>, when using ExpectedException:</p>\n<p>Keep in mind that your expected exception will be wrapped in an InvocationTargetException, so in order to get to your exception you will have to throw the cause of the InvocationTargetException you received. Something like (testing private method validateRequest() on BizService):</p>\n<pre><code>@Rule\npublic ExpectedException thrown = ExpectedException.none();\n\n@Autowired(required = true)\nprivate BizService svc;\n\n\n@Test\npublic void testValidateRequest() throws Exception {\n\n    thrown.expect(BizException.class);\n    thrown.expectMessage(expectMessage);\n\n    BizRequest request = /* Mock it, read from source - file, etc. */;\n    validateRequest(request);\n}\n\nprivate void validateRequest(BizRequest request) throws Exception {\n    Method method = svc.getClass().getDeclaredMethod(&quot;validateRequest&quot;, BizRequest.class);\n    method.setAccessible(true);\n    try {\n        method.invoke(svc, request);\n    }\n    catch (InvocationTargetException e) {\n        throw ((BizException)e.getCause());\n    }\n }\n</code></pre>\n'}, {'answer_id': 39215279, 'author': 'GROX13', 'author_id': 3930424, 'author_profile': 'https://Stackoverflow.com/users/3930424', 'pm_score': 4, 'selected': False, 'text': '<p>I would suggest you refactoring your code a little bit. When you have to start thinking about using reflection or other kind of stuff, for just testing your code, something is going wrong with your code.</p>\n<p>You mentioned different types of problems. Let\'s start with private fields. In case of private fields I would have added a new constructor and injected fields into that. Instead of this:</p>\n<pre><code>public class ClassToTest {\n\n    private final String first = &quot;first&quot;;\n    private final List&lt;String&gt; second = new ArrayList&lt;&gt;();\n    ...\n}\n</code></pre>\n<p>I\'d have used this:</p>\n<pre><code>public class ClassToTest {\n\n    private final String first;\n    private final List&lt;String&gt; second;\n\n    public ClassToTest() {\n        this(&quot;first&quot;, new ArrayList&lt;&gt;());\n    }\n\n    public ClassToTest(final String first, final List&lt;String&gt; second) {\n        this.first = first;\n        this.second = second;\n    }\n    ...\n}\n</code></pre>\n<p>This won\'t be a problem even with some legacy code. Old code will be using an empty constructor, and if you ask me, refactored code will look cleaner, and you\'ll be able to inject necessary values in test without reflection.</p>\n<p>Now about private methods. In my personal experience when you have to stub a private method for testing, then that method has nothing to do in that class. A common pattern, in that case, would be to <em>wrap</em> it within an interface, like <code>Callable</code> and then you pass in that interface also in the constructor (with that multiple constructor trick):</p>\n<pre><code>public ClassToTest() {\n    this(...);\n}\n\npublic ClassToTest(final Callable&lt;T&gt; privateMethodLogic) {\n    this.privateMethodLogic = privateMethodLogic;\n}\n</code></pre>\n<p>Mostly all that I wrote looks like it\'s a <a href="https://en.wikipedia.org/wiki/Dependency_injection" rel="nofollow noreferrer">dependency injection</a> pattern. In my personal experience it\'s really useful while testing, and I think that this kind of code is cleaner and will be easier to maintain. I\'d say the same about nested classes. If a nested class contains heavy logic it would be better if you\'d moved it as a package private class and have injected it into a class needing it.</p>\n<p>There are also several other design patterns which I have used while refactoring and maintaining legacy code, but it all depends on cases of your code to test. Using reflection mostly is not a problem, but when you have an enterprise application which is heavily tested and tests are run before every deployment everything gets really slow (it\'s just annoying and I don\'t like that kind of stuff).</p>\n<p>There is also setter injection, but I wouldn\'t recommended using it. I\'d better stick with a constructor and initialize everything when it\'s really necessary, leaving the possibility for injecting necessary dependencies.</p>\n'}, {'answer_id': 46121866, 'author': 'Rahul', 'author_id': 7599315, 'author_profile': 'https://Stackoverflow.com/users/7599315', 'pm_score': 1, 'selected': False, 'text': '<p>You can use <a href="https://en.wikipedia.org/wiki/Mockito" rel="nofollow noreferrer">PowerMockito</a> to set return values for private fields and private methods that are called/used in the private method you want to test:</p>\n<p>For example, setting a return value for a private method:</p>\n<pre><code>MyClient classUnderTest = PowerMockito.spy(new MyClient());\n\n// Set the expected return value\nPowerMockito.doReturn(20).when(classUnderTest, &quot;myPrivateMethod&quot;, anyString(), anyInt());\n// This is very important. Otherwise, it will not work\nclassUnderTest.myPrivateMethod();\n\n// Setting the private field value as someValue:\nWhitebox.setInternalState(classUnderTest, &quot;privateField&quot;, someValue);\n</code></pre>\n<p>Then finally you can validate your private method under test is returning the correct value based on set values above by:</p>\n<pre><code>String msg = Whitebox.invokeMethod(obj, &quot;privateMethodToBeTested&quot;, &quot;param1&quot;);\nAssert.assertEquals(privateMsg, msg);\n</code></pre>\n<p>Or</p>\n<p>If the classUnderTest private method does not return a value, but it sets another private field then you can get that private field value to see if it was set correctly:</p>\n<pre><code>// To get the value of a private field\nMyClass obj = Whitebox.getInternalState(classUnderTest, &quot;foo&quot;);\nassertThat(obj, is(notNull(MyClass.class))); // Or test value\n</code></pre>\n'}, {'answer_id': 47004093, 'author': 'Miladinho', 'author_id': 4836141, 'author_profile': 'https://Stackoverflow.com/users/4836141', 'pm_score': 2, 'selected': False, 'text': '<p>If you are worried by not testing private methods as many of the posts suggest, consider that a <strong>code coverage</strong> tool will determine exactly how much of your code is tested and where it leaks, so it is quantifiably acceptable to do this.</p>\n<p>Answers that direct the author of the question towards a \'workaround\' are doing a massive disservice to the community. Testing is a major part of all engineering disciplines. You would not want to buy a car that is not properly tested, and tested in a meaningful way, so why would anyone want to buy or use software that is tested poorly? The reason people do this anyway is probably because the effects of badly tested software are felt way after the fact, and we don\'t usually associate them with bodily harm.</p>\n<p>This is a very dangerous perception which will be difficult to change, but it is our responsibility to deliver safe products regardless of what even management is bullying us to do. Think <a href="https://en.wikipedia.org/wiki/2017_Equifax_data_breach#Data_breach" rel="nofollow noreferrer">the Equifax hack</a>...</p>\n<p>We must strive to build an environment that encourages good software engineering practices. This does not mean ostracizing the weak/lazy among us who do not take their craft seriously, but rather, to create a status quo of accountability and self reflection that would encourage everyone to pursue growth, both mentally and skillfully.</p>\n<p>I am still learning, and may have wrong perceptions/opinions myself, but I do firmly believe that we need to hold ourselves accountable to good practices and shun irresponsible hacks or workarounds to problems.</p>\n'}, {'answer_id': 47454552, 'author': 'Android is everything for me', 'author_id': 1550509, 'author_profile': 'https://Stackoverflow.com/users/1550509', 'pm_score': 2, 'selected': False, 'text': '<p>The best and proper legal way to test a Java private method from a test framework is the <strong>@VisibleForTesting</strong> annotation over the method, so the same method will be visible for the test framework like a public method.</p>\n'}, {'answer_id': 48182688, 'author': 'mohammad madani', 'author_id': 1125774, 'author_profile': 'https://Stackoverflow.com/users/1125774', 'pm_score': 3, 'selected': False, 'text': '<p>In <a href="https://en.wikipedia.org/wiki/C%2B%2B" rel="nofollow noreferrer">C++</a>: before including the class header that has a private function that you want to test.</p>\n<p>Use this code:</p>\n<pre class="lang-cpp prettyprint-override"><code>#define private public\n#define protected public\n</code></pre>\n'}, {'answer_id': 48430793, 'author': 'Victor Grazi', 'author_id': 522729, 'author_profile': 'https://Stackoverflow.com/users/522729', 'pm_score': 4, 'selected': False, 'text': '<p><a href="https://meta.stackexchange.com/questions/184108/what-is-syntax-highlighting-and-how-does-it-wok/184109#184109">PowerMockito</a> is made for this.</p>\n<p>Use a <a href="https://en.wikipedia.org/wiki/Apache_Maven" rel="nofollow noreferrer">Maven</a> dependency:</p>\n<pre class="lang-xml prettyprint-override"><code>    &lt;dependency&gt;\n        &lt;groupId&gt;org.powermock&lt;/groupId&gt;\n        &lt;artifactId&gt;powermock-core&lt;/artifactId&gt;\n        &lt;version&gt;2.0.7&lt;/version&gt;\n        &lt;scope&gt;test&lt;/scope&gt;\n    &lt;/dependency&gt;\n</code></pre>\n<p>Then you can do</p>\n<pre><code>import org.powermock.reflect.Whitebox;\n...\nMyClass sut = new MyClass();\nSomeType rval = Whitebox.invokeMethod(sut, &quot;myPrivateMethod&quot;, params, moreParams);\n</code></pre>\n'}, {'answer_id': 51081607, 'author': 'HilaB', 'author_id': 8356771, 'author_profile': 'https://Stackoverflow.com/users/8356771', 'pm_score': 1, 'selected': False, 'text': '<p>My team and I are using Typemock, which has an API that allows you to <a href="https://www.typemock.com/docs/?book=Isolator&amp;page=Documentation%2FHtmlDocs%2Fcontrollingnonpublicmethods.htm" rel="nofollow noreferrer">fake non-public methods</a>.</p>\n<p>Recently they added the ability to <a href="https://www.typemock.com/docs/?book=Isolator&amp;page=Documentation%2FHtmlDocs%2Ffakingnonpublicobjects.htm" rel="nofollow noreferrer">fake non-visible types</a> and to use <a href="https://en.wikipedia.org/wiki/XUnit" rel="nofollow noreferrer">xUnit</a>.</p>\n'}, {'answer_id': 52455476, 'author': 'AR1', 'author_id': 2300013, 'author_profile': 'https://Stackoverflow.com/users/2300013', 'pm_score': 1, 'selected': False, 'text': '<p>If you have a case where you really need to test a private method/class etc.. directly, you can use reflection as already mentioned in other answers. However if it comes to that, instead of dealing directly with reflection I\'d rather use utility classes provided by your framework. For instance, for Java we have:</p>\n<ul>\n<li><p><a href="https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/util/ReflectionUtils.html" rel="nofollow noreferrer">ReflectionUtils</a> in <a href="https://en.wikipedia.org/wiki/Spring_Framework" rel="nofollow noreferrer">Spring Framework</a></p>\n</li>\n<li><p><a href="https://junit.org/junit5/docs/5.0.3/api/org/junit/platform/commons/util/ReflectionUtils.html" rel="nofollow noreferrer">ReflectionUtils</a> in <a href="https://en.wikipedia.org/wiki/JUnit" rel="nofollow noreferrer">JUnit</a></p>\n</li>\n</ul>\n<p>As per how to use them, you can find plenty of articles online. Here one that I particularly liked:</p>\n<ul>\n<li><a href="https://www.programcreek.com/java-api-examples/index.php?api=org.springframework.util.ReflectionUtils" rel="nofollow noreferrer">Java Code Examples for org.springframework.util.ReflectionUtils</a></li>\n</ul>\n'}, {'answer_id': 53768967, 'author': 'Louis Saglio', 'author_id': 7629797, 'author_profile': 'https://Stackoverflow.com/users/7629797', 'pm_score': 1, 'selected': False, 'text': '<p>You can create a special public method to proxy the private method to test.\nThe @TestOnly annotation is out of the box available when using IntelliJ.\nThe downside is is that if somebody want to to use the private method in a public context, he can do it. But he will be warned by the annotation and the method name. On IntelliJ a warning will appear when doing it.</p>\n\n<pre><code>import org.jetbrains.annotations.TestOnly\n\nclass MyClass {\n\n    private void aPrivateMethod() {}\n\n    @TestOnly\n    public void aPrivateMethodForTest() {\n        aPrivateMethod()\n    }\n}\n</code></pre>\n'}, {'answer_id': 55588184, 'author': 'Ercan', 'author_id': 4308897, 'author_profile': 'https://Stackoverflow.com/users/4308897', 'pm_score': 0, 'selected': False, 'text': '<p>There is another approach to test your private methods.\nIf you "enable assertion" in run configurations then you can unit test your method inside method itself. For example;</p>\n\n<pre><code>assert ("Ercan".equals(person1.name));\nassert (Person.count == 2);\n</code></pre>\n'}, {'answer_id': 56100192, 'author': 'WesternGun', 'author_id': 4537090, 'author_profile': 'https://Stackoverflow.com/users/4537090', 'pm_score': 2, 'selected': False, 'text': '<p><code>PowerMock.Whitebox</code> is the best option I have seen, but when I read its source code, it reads private fields with reflection, so I think I have my answer: </p>\n\n<ul>\n<li>test private internal states(fields) with PowerMock, or just reflection without the overhead of introducing another independency</li>\n<li>for private methods: actually, the upvote for this question itself, and the huge number of comments and answers, shows that it is a very concurrent and controversial topic <strong>where no definite answer could be given to suit every circumstance</strong>. I understand that only contract should be tested, but we also have coverage to consider. Actually, <strong>I doubt that only testing contracts will 100% make a class immune to errors</strong>. Private methods are those who process data in the class where it is defined and thus does not interest other classes, so we cannot simply expose to make it testable. I will <strong>try not to test them</strong>, but when you have to, <strong>just go for it and forget all the answers here</strong>. You know better your situation and restrictions than any other one in the Internet. When you have control over your code, use that. With consideration, but without over-thinking. </li>\n</ul>\n\n<hr>\n\n<p>After some time, when I reconsider it, I still believe this is true, but I saw better approaches.</p>\n\n<p>First of all, <code>Powermock.Whitebox</code> is still usable. </p>\n\n<p>And, Mockito <code>Whitebox</code> has been hidden after v2(the latest version I can find with <code>Whitebox</code> is <code>testImplementation \'org.mockito:mockito-core:1.10.19\'</code>) and it has always been part of <code>org.mockito.internal</code> package, which is prone of breaking changes in the future(see <a href="https://stackoverflow.com/questions/40280918/what-do-i-use-instead-of-whitebox-in-mockito-2-2-to-set-fields">this post</a>). So now I tend not to use it. </p>\n\n<p>In Gradle/Maven projects, if you define private methods or fields, there is no other ways then reflection to get access to them, so the first part stays true. But, if you change the visibility to "package private", <strong>the tests following the same structure in <code>test</code> package will have access to them.</strong> That is also another important reason why we are encouraged to create the same hierarchy in <code>main</code> and <code>test</code> package. So, when you have control over production code as well as tests, delete that <code>private</code> access modifier may be the best option for you because relatively it does not cause huge impact. And, that makes testing as well as <strong>private method spying</strong> possible.</p>\n\n<pre class="lang-java prettyprint-override"><code>@Autowired\nprivate SomeService service; // with a package private method "doSomething()"\n\n@Test\nvoid shouldReturnTrueDoSomething() {\n    assertThat(doSomething(input), is(true)); // package private method testing\n}\n\n@Test\nvoid shouldReturnTrueWhenServiceThrowsException() {\n    SomeService spy = Mockito.spy(service); // spying real object\n    doThrow(new AppException()).when(spy).doSomething(input); // spy package private method\n    ...\n\n}\n</code></pre>\n\n<p>When it comes to internal fields, in Spring you have <code>ReflectionUtils.setField()</code>. </p>\n\n<p>At last, sometimes we can bypass the problem itself: if there is a coverage requirement to meet, maybe you can move these private methods into an inner static class and ignore this class in Jacoco. I just found some way to ignore inner class in Jacoco gradle tasks. <a href="https://stackoverflow.com/questions/58604955/how-to-ignore-inner-static-classes-in-jacoco-when-using-gradle">another question</a></p>\n'}, {'answer_id': 57010282, 'author': 'yoAlex5', 'author_id': 4770877, 'author_profile': 'https://Stackoverflow.com/users/4770877', 'pm_score': 2, 'selected': False, 'text': '<p>Android has <a href="https://developer.android.com/studio/write/annotations.html#visible" rel="nofollow noreferrer"><code>@VisibleForTesting</code></a> annotation from <code>android.support.annotation</code> package.</p>\n\n<blockquote>\n  <p>The <code>@VisibleForTesting</code> annotation indicates that an annotated method is more visible than normally necessary to make the method testable. This annotation has an optional <code>otherwise</code> argument that lets you designate what the visibility of the method should have been if not for the need to make it visible for testing. Lint uses the <code>otherwise</code> argument to enforce the intended visibility.</p>\n</blockquote>\n\n<p>On the practice it means that you should make a method open for testing and the <code>@VisibleForTesting</code> annotation will show a warning.</p>\n\n<p>For example</p>\n\n<pre><code>package com.mypackage;\n\npublic class ClassA {\n\n    @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)\n    static void myMethod() {\n\n    }\n}\n</code></pre>\n\n<p>And when you call ClassA.myMethod() within the same package(com.mypackage) you will see the warning.</p>\n\n<p><a href="https://i.stack.imgur.com/25FX3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/25FX3.png" alt="enter image description here"></a></p>\n'}, {'answer_id': 57514468, 'author': 'avtomaton', 'author_id': 2915032, 'author_profile': 'https://Stackoverflow.com/users/2915032', 'pm_score': 0, 'selected': False, 'text': "<p>For C++ (since C++11) adding the test class as a friend works perfectly and does not break production encapsulation.</p>\n\n<p>Let's suppose that we have some class <code>Foo</code> with some private functions which really require testing, and some class <code>FooTest</code> that should have access to Foo's private members. Then we should write the following:</p>\n\n<pre><code>// prod.h: some production code header\n\n// forward declaration is enough\n// we should not include testing headers into production code\nclass FooTest;\n\nclass Foo\n{\n  // that does not affect Foo's functionality\n  // but now we have access to Foo's members from FooTest\n  friend FooTest;\npublic:\n  Foo();\nprivate:\n  bool veryComplicatedPrivateFuncThatReallyRequiresTesting();\n}\n</code></pre>\n\n<pre><code>// test.cpp: some test\n#include &lt;prod.h&gt;\n\nclass FooTest\n{\npublic:\n  void complicatedFisture() {\n    Foo foo;\n    ASSERT_TRUE(foo.veryComplicatedPrivateFuncThatReallyRequiresTesting());\n  }\n}\n\nint main(int /*argc*/, char* argv[])\n{\n  FooTest test;\n  test.complicatedFixture();  // and it really works!\n}\n</code></pre>\n"}, {'answer_id': 58452308, 'author': 'Mukundhan', 'author_id': 6769119, 'author_profile': 'https://Stackoverflow.com/users/6769119', 'pm_score': 0, 'selected': False, 'text': '<p>The following <strong>Reflection TestUtil</strong> could be <strong><em>used generically</em></strong> to test the <strong><em>private methods for their atomicity</em></strong>.</p>\n\n<pre><code>import com.google.common.base.Preconditions;\n\nimport org.springframework.test.util.ReflectionTestUtils;\n\n/**\n * &lt;p&gt;\n * Invoker\n * &lt;/p&gt;\n *\n * @author\n * @created Oct-10-2019\n */\npublic class Invoker {\n    private Object target;\n    private String methodName;\n    private Object[] arguments;\n\n    public &lt;T&gt; T invoke() {\n        try {\n            Preconditions.checkNotNull(target, "Target cannot be empty");\n            Preconditions.checkNotNull(methodName, "MethodName cannot be empty");\n            if (null == arguments) {\n                return ReflectionTestUtils.invokeMethod(target, methodName);\n            } else {\n                return ReflectionTestUtils.invokeMethod(target, methodName, arguments);\n            }\n        } catch (Exception e) {\n           throw e;\n        }\n    }\n\n    public Invoker withTarget(Object target) {\n        this.target = target;\n        return this;\n    }\n\n    public Invoker withMethod(String methodName) {\n        this.methodName = methodName;\n        return this;\n    }\n\n    public Invoker withArguments(Object... args) {\n        this.arguments = args;\n        return this;\n    }\n\n}\n\nObject privateMethodResponse = new Invoker()\n  .withTarget(targetObject)\n  .withMethod(PRIVATE_METHOD_NAME_TO_INVOKE)\n  .withArguments(arg1, arg2, arg3)\n  .invoke();\nAssert.assertNotNutll(privateMethodResponse)\n</code></pre>\n'}, {'answer_id': 59762243, 'author': 'Vishwas', 'author_id': 4458900, 'author_profile': 'https://Stackoverflow.com/users/4458900', 'pm_score': 1, 'selected': False, 'text': '<p>If you are only using <a href="https://en.wikipedia.org/wiki/Mockito" rel="nofollow noreferrer">Mockito</a>:</p>\n<p>You can consider the private method as a part of public method being tested. You can make sure you cover all the cases in private method when testing public method.</p>\n<p>Suppose you are a Mockito-only user (you are not allowed or don\'t want to use <a href="https://de.wikipedia.org/wiki/PowerMock" rel="nofollow noreferrer">PowerMock</a> or reflection or any such tools) and you don’t want to change the existing code or libraries being tested, this might be the best way.</p>\n<p>The only thing you need to handle if you choose this way is the variables (user-defined objects) declared locally within private methods.  If the private method depends on locally declared variable objects and their methods, make sure you declare those user-defined objects globally as private object instead of locally declared objects. You can instantiate these objects locally.</p>\n<p>This allows you to <a href="https://en.wikipedia.org/wiki/Mock_object" rel="nofollow noreferrer">mock</a> these objects and inject them back to testing object. You can also mock (using when/then) their methods.</p>\n<p>This will allow you test private method without errors when testing the public method.</p>\n<p>Advantages</p>\n<ol>\n<li>Code coverage</li>\n<li>Able to test the complete private method.</li>\n</ol>\n<p>Disadvantages</p>\n<ol>\n<li>Scope of the object—if you don\'t want the object to be exposed to other methods within same class, this might not be your way.</li>\n<li>You might end up testing the private method multiple times when invoked at different public methods and/or in the same method multiple times.</li>\n</ol>\n'}, {'answer_id': 60675043, 'author': 'Abhishek Sengupta', 'author_id': 9389293, 'author_profile': 'https://Stackoverflow.com/users/9389293', 'pm_score': 2, 'selected': False, 'text': '<p>Hey use this utility class if you are on <strong>spring</strong>.</p>\n\n<pre><code>ReflectionTestUtils.invokeMethod(new ClassName(), "privateMethodName");\n</code></pre>\n'}, {'answer_id': 62632701, 'author': 'Ahmed Hussein', 'author_id': 7280140, 'author_profile': 'https://Stackoverflow.com/users/7280140', 'pm_score': -1, 'selected': False, 'text': '<p>In your class:</p>\n<pre><code>namespace my_namespace {\n    #ifdef UNIT_TEST\n        class test_class;\n    #endif\n\n    class my_class {\n        public:\n            #ifdef UNIT_TEST\n                friend class test_class;\n            #endif\n        private:\n            void fun() { cout &lt;&lt; &quot;I am private&quot; &lt;&lt; endl; }\n    }\n}\n</code></pre>\n<p>In your unit test class:</p>\n<pre><code>#ifndef UNIT_TEST\n    #define UNIT_TEST\n#endif\n\n#include &quot;my_class.h&quot;\n\nclass my_namespace::test_class {\n    public:\n        void fun() { my_obj.fun(); }\n    private:\n        my_class my_obj;\n}\n\nvoid my_unit_test() {\n    test_class test_obj;\n    test_obj.fun(); // here you accessed the private function ;)\n}\n</code></pre>\n'}, {'answer_id': 63069114, 'author': 'm.nguyencntt', 'author_id': 3110488, 'author_profile': 'https://Stackoverflow.com/users/3110488', 'pm_score': 2, 'selected': False, 'text': '<p>Here is my <a href="https://projectlombok.org/features/" rel="nofollow noreferrer">Lombok</a> sample:</p>\n<pre><code>public static void main(String[] args) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {\n    Student student = new Student();\n\n    Field privateFieldName = Student.class.getDeclaredField(&quot;name&quot;);\n    privateFieldName.setAccessible(true);\n    privateFieldName.set(student, &quot;Naruto&quot;);\n\n    Field privateFieldAge = Student.class.getDeclaredField(&quot;age&quot;);\n    privateFieldAge.setAccessible(true);\n    privateFieldAge.set(student, &quot;28&quot;);\n\n    System.out.println(student.toString());\n\n    Method privateMethodGetInfo = Student.class.getDeclaredMethod(&quot;getInfo&quot;, String.class, String.class);\n    privateMethodGetInfo.setAccessible(true);\n    System.out.println(privateMethodGetInfo.invoke(student, &quot;Sasuke&quot;, &quot;29&quot;));\n}\n\n\n@Setter\n@Getter\n@ToString\nclass Student {\n    private String name;\n    private String age;\n    \n    private String getInfo(String name, String age) {\n        return name + &quot;-&quot; + age;\n    }\n}\n</code></pre>\n'}, {'answer_id': 67065816, 'author': 'Rinke', 'author_id': 12592592, 'author_profile': 'https://Stackoverflow.com/users/12592592', 'pm_score': 2, 'selected': False, 'text': "<p>I think most answers are too crude. It depends on your code if you should test private methods or not.</p>\n<p>I used private method testing in the past, and I did this by reflection. It works for me. I realize the problems with it, but for me it was the best sollution.</p>\n<p>I have a heavy application that simulates human behaviour in a population of over a million persons. Every person is represented by an object. The main purpose of the application is to follow how something (disease, information, ideas) spreads through the population.</p>\n<p>For this I have methods that pass on the disease or information from one object to another. There is absolutely no reason to make these methods public, for the end user is not interested in one pass from person to person. The end user is only interested in the grand picture of how it spreads through the population. So those methods are private.</p>\n<p>But I want to know for sure if the single act of passing one bit of information from one person to another is doing what it should. Testing it via public user interfaces is also not possible, because it's just not public, and I think it's awkward to make it public just for the purpose of testing. The end output of the application is defined by hundreds of millions of such single steps being performed all the time. I cannot test the end output either, because that has complicated stochastability involved, which makes it too unpredictable to test.</p>\n<p>So the way for me to test the application is by testing a single step of passing information from one person to another person. These are all private methods. And so I use reflection to test that.</p>\n<p>I'm telling this story to show that it's not that plain black and white story. It depends on your application what is best. Under some circumstances, testing private methods via reflection might be your best option.</p>\n<p>If some people here know better solutions in my use case, I'd happily stand corrected of course....</p>\n"}, {'answer_id': 67122309, 'author': 'Saša', 'author_id': 897373, 'author_profile': 'https://Stackoverflow.com/users/897373', 'pm_score': 3, 'selected': False, 'text': '<p>I want to share a rule I have about testing which particularly is related to this topic:</p>\n<blockquote>\n<p>I think that you should never adapt production code in order to\nindulge easer writing of tests.</p>\n</blockquote>\n<p><em>There are a few suggestions in other posts saying you should adapt the original class in order to test a private method - please red this warning first.</em></p>\n<p>If we change the accessibility of a method/field to package private or protected, just in order to have it accessible to tests, then we defeat the purpose of existence of private access directive.</p>\n<p>Why should we have private fields/methods/classes at all when we want to have <a href="https://en.wikipedia.org/wiki/Test-driven_development" rel="nofollow noreferrer">test-driven development</a>? Should we declare everything as package private, or even public then, so we can test without any effort?—I don\'t think so.</p>\n<p>From another point of view: <em>Tests should not burden performance and execution of the production application.</em></p>\n<p>If we change production code just for the sake of easier testing, that may burden performance and the execution of the application in some way.</p>\n<p>If someone starts to change private access to package private, then a developer may eventually come up to other &quot;ingenious ideas&quot; about adding even more code to the original class. This would make additional noise to readability and can burden the performance of the application.</p>\n<p>With changing of a private access to some less restrictive, we are opening the possibility to a developer for misusing the new situation in the future development of the application. Instead of enforcing him/her to develop in the proper way, we are tempting him/her with new possibilities and giving him ability to make wrong choices in the future.</p>\n<p>Of course there might be a few exceptions to this rule, but with clear understanding, what is the rule and what is the exception? We need to be absolutely sure we know why that kind of exception is introduced.</p>\n'}, {'answer_id': 70938111, 'author': 'd3rbastl3r', 'author_id': 2893873, 'author_profile': 'https://Stackoverflow.com/users/2893873', 'pm_score': 1, 'selected': False, 'text': '<p>I feel exactly the same ... change the access modifier for a method just to be able to run a test looks for me as a bad idea. Also in our company we had a lot of discussions about it and in my opinion, really nice way to test a private method is to using Java reflection or another framework which making the method testable. I did so multiple times for complex private methods and this helped me to keep the test small, readable and maintainable.</p>\n<p>After I have read all the answers here, I just disagree with persons who say &quot;if you need to test a private method, then there is a code smell&quot; or even &quot;don´t test private methods&quot; ... so I have a little example for you:</p>\n<p>Imagine I have a class with one public method and a couple of private methods:</p>\n<pre><code>public class ConwaysGameOfLife {\n\n    private boolean[][] generationData = new boolean[128][128];\n\n    /**\n     * Compute the next generation and return the new state\n     * Also saving the new state in generationData\n     */\n    public boolean[][] computeNextGeneration() {\n        boolean[][] tempData = new boolean[128][128];\n\n        for (int yPos=0; yPos&lt;=generationData.length; yPos++) {\n            for (int xPos=0; xPos&lt;=generationData[yPos].length; xPos++) {\n                int neighbors = countNeighbors(yPos, xPos);\n                tempData[yPos][xPos] = determineCellState(neighbors, yPos, xPos);\n            }\n        }\n\n        generationData = tempData;\n        return generationData;\n    }\n\n    /**\n     * Counting the neighbors for a cell on given position considering all the edge cases\n     *\n     * @return the amount of found neighbors for a cell\n     */\n    private int countNeighbors(int yPos, int xPos) {}\n\n    /**\n     * Determine the cell state depending on the amount of neighbors of a cell and on a current state of the cell\n     *\n     * @return the new cell state\n     */\n    private boolean determineCellState(int neighborsAmount, int yPos, int xPos) {}\n}\n</code></pre>\n<p>So at least for the method &quot;countNeighbors&quot; I need to test eight edge cases and also some general cases (cells directly in the corners, cells directly on the edges of the matrix and cells somewhere in the middle). So if I am only trying to cover all the cases through the &quot;computeNextGeneration&quot; method and after refactoring, some tests are red, it is probably time consuming to identify the place where the bug is.</p>\n<p>If I am testing &quot;determineCellState&quot; and &quot;countNeighbors&quot; separately and after refactoring and optimization, tests of &quot;computeNextGeneration&quot; and &quot;determineCellState&quot; are red, I am pretty sure that the error will be in the &quot;determineCellState&quot; method.</p>\n<p>Also, if you write unit tests for those methods from the beginning, this tests will help you to develop the methods / the algorithms without a need to considering and wrapping other method calls and cases inside the public method. You can just write fast small tests covering your cases in the method ... for example if the test with the name &quot;countNeighbors_should_return_right_amount_of_neighbors_for_the_right_top_corner_cell()&quot; fails, then it is pretty clear where to look for the bug.</p>\n'}]
['https://Stackoverflow.com/questions/34571', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3098/']