Some might say that testing private methods should be avoided because it means not testing the contract, that is the interface implemented by the class, but the internal implementation of the class itself. Still, not all classes were designed with testability in mind, so real life compromises sometimes demand such a trick.
When writing unit tests in C# with MSTest, the PrivateObject class lets you easily call private methods:
- [TestMethod]
- public void TestLPRead()
- {
- var Logger = A.Fake<ILogger>();
- var Telemetry = A.Fake<ITelemetry>();
- DefaultDataModel DM = new DefaultDataModel(Logger, Telemetry);
- PrivateObject obj = new PrivateObject(DM);
- List<LPRead> ReadsList = (List<LPRead>)obj.Invoke(“GetReads”);
In the code above, a PrivateObject instance is created passing an instance of the class to be tested
- PrivateObject obj = new PrivateObject(DM);
then the invocation of the private method, that would be
- List<LPRead> ReadsList = DM.GetReads();
if the method were public, becomes
- List<LPRead> ReadsList = (List<LPRead>)obj.Invoke(“GetReads”);