title: How can I use PrivateObject to access private members of both my class and its parent?
body: <p>I'm testing a class that is part of a hierarchy. I've been setting up my test classes with the object under test, and a <code>PrivateObject</code> to allow access to that object. I'm getting exceptions when I attempt to access private members of the parent class. </p>
  
  <p>The only workaround I've found so far is to pass a <code>PrivateType</code> specifying the base class to the <code>PrivateObject</code> constructor, but then it doesn't work on private members of the subclass. </p>
  
  <p>Is there some way I can do this, perhaps by using the binding flags parameter on the Get* methods of Private object?</p>
  
  <p>I did try using the automatically-generated Accessor classes (right-click in the main class, Create Private Accessor). However, that's worse: It shows a property I can read, but it throws the same exception as PrivateObject does, and there's no other options I can use (binding flags or whatnot) to fix the exception.</p>
  
  <p>Here's my sample test code. I'd like there to be some way to construct and use the PrivateObject to retrieve both fields. </p>
  
  <pre><code>public class BaseClass
  {
      private int one = 1;
  }
  
  public class SubClass : BaseClass
  {
      private int two = 2;
  }
  
  [TestClass]
  public class UnitTest1
  {
      BindingFlags flags = BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
  
      [TestMethod]
      public void TestMethod1()
      {
          SubClass test = new SubClass();
          PrivateObject priv = new PrivateObject(test);
  
          Assert.AreNotEqual&lt;int&gt;(0, (int)priv.GetFieldOrProperty("one", flags)); // System.MissingMethodException: Method 'PrivateObjectTester.SubClass.one' not found.
          Assert.AreNotEqual&lt;int&gt;(0, (int)priv.GetFieldOrProperty("two", flags));
      }
  
      [TestMethod]
      public void TestMethod2()
      {
          SubClass test = new SubClass();
          PrivateObject priv = new PrivateObject(test, new PrivateType(typeof(BaseClass)));
  
          Assert.AreNotEqual&lt;int&gt;(0, (int)priv.GetFieldOrProperty("one", flags));
          Assert.AreNotEqual&lt;int&gt;(0, (int)priv.GetFieldOrProperty("two", flags)); // System.MissingMethodException: Method 'PrivateObjectTester.BaseClass.two' not found.
      }
  }
  </code></pre>