How to: Test a Private Method
You can test both public and private methods using unit tests. As with public methods, unit tests for private methods are created automatically when you generate tests from the code you want to test.
Although you can manually
How to: Test a Private Method
You can test both public and private methods using unit tests. As with public methods, unit tests for private methods are created automatically when you generate tests from the code you want to test.
Although you can manually code unit tests to test any method, this task is more difficult for private than for public methods because it requires a deeper understanding of the intricacies of reflection. You will therefore find it advantageous to generate tests for private methods instead of coding them by hand.
When you generate a unit test for a private method, a private accessor is automatically created. A private accessor is a method that the test method uses to access the private code. The unit test generates a call to the private accessor, and then calls the private method through the private accessor. The private accessor resides in a file that is part of your test project; therefore it is compiled into your test project assembly.
If the signature for a private method changes, you must update the unit test that exercises that private method. For more information, see.
To generate a unit test for a private method
Open a source code file that contains a private method.
Right-click the private method, and select Create Unit Tests.
This displays the Create Unit Tests dialog box. In the visible tree structure, only check box for the private method is selected.
(Optional) In the Create Unit Tests dialog box, you can change the Output project. You can also click Settings to reconfigure the way unit tests are generated.
This creates a new file named VSCodeGenAccessors, which contains special accessor methods that retrieve values of private entities in the class being tested. You can see the new file displayed in Solution Explorer in the test project folder.
If your test project had no unit tests before this point, a source code file to house unit tests is also created. As with the file that contains private accessors, the file that contains unit tests is also visible in your test project in Solution Explorer.
Open the file that contains your unit tests and scroll to the test for the private method. Find the statements that are marked with // TODO: comments and complete them by following the directions in the comments. This helps the test produce more accurate results. For more information, see.
The unit test for the private method is now ready to run. For information about running unit tests, see.