How to create an instance of PrivateType of an internal private class

I tried to set up unit test for a private inner class, but had very little success:

namespace Stats.Model
{
  public class DailyStat
  {
    private class DailyStatKey // The one to test
    {
      private DateTime date;
      public DateTime Date 
      { 
        get { return date; }
        set { date = value.Date; }
      }

      public StatType Type { get; set; }

      public override int GetHashCode()
      {
        return Date.Year * 1000000 +
               Date.Month * 10000 +
               Date.Day * 100 +
               (int)Type;
      }

      public override bool Equals(object obj)
      {
        DailyStatKey otherKey = obj as DailyStatKey;
        if (otherKey == null)
          return false;
        return (this.Date == otherKey.Date && this.StatType == otherKey.StatType);
      }
    }
  }
}

I tried this code:

PrivateType statKeyType = new PrivateType("Stats.Model", "Stats.Model.DailyStat.DailyStatKey");

and

PrivateType statKeyType = new PrivateType("Stats.Model", "DailyStat.DailyStatKey");

To no avail.

The assembly name is "Stats.Model" and for me the type name looks correct, but I just get an exception: "System.TypeLoadException: failed to load type"

So what am I doing wrong?

PrivateType, as far as I know, is based on reflection, and I would suggest that it is largely intended for this scenario, since you cannot have a private class directly below the namespace.

EDIT:

Added full implementation of DailyStatKey. What I want to check out is the uniqueness of the GetHashCode method. As you can see, I'm trying to set date + type to one int.

+5
4

:

var parentType = typeof(DailyStat);
var keyType = parentType.GetNestedType("DailyKeyStat", BindingFlags.NonPublic); 
//edited to use GetNestedType instead of just NestedType

var privateKeyInstance = new PrivateObject(Activator.CreateInstance(keyType, true));

privateKeyInstance.SetProperty("Date", DateTime.Now);
privateKeyInstance.SetProperty("Type", StatType.Foo);

var hashCode = (int)privateKeyInstance.Invoke("GetHashCode", null);
+5

PrivateType :

PrivateType statKeyType = new PrivateType("Stats.Model", "Stats.Model.DailyStat+DailyStatKey");

, ( Stats.Model.DailyStat.DailyStatKey), .

+3

, , , DailyStat. (), , , , ,

EDIT:

Since you are trying to do this for unit testing, then you should not test this class because it is private. You could test it only through any open interface DailyStat.

+1
source

You can code the public method GetDailyStatKey in the parent class.

public class DailyStat
{
    private class DailyStatKey // The one to test 
    {
    }
    public DailyStatKey GetDailyStatKey()
    {
        return new  DailyStatKey();
    }
}

Now you can write:

DailyStat v = new DailyStat();
var x =  v.GetDailyStatKey();
-2
source

All Articles