Ico826
Ico826

Reputation: 29

C#: How can I instantiate a List of private inner class?

everybody. I'm doing unit-testing now, while I have a problem I can not solve it by my own. The problem is listed below:

public class A {
    private class B{ }
    private List<B> list = new List<B>;
}

I want to test whether list[i] is null or not? Now I can use Reflection to get the list, But the question is how can I add a instance of B into the list? Thanks for your help!

Upvotes: 1

Views: 159

Answers (2)

zaitsman
zaitsman

Reputation: 9509

In general, just testing this piece of code is not productive. While i disagree with the other answer you got re: not testing privates, the test should be meaningful to the behaviour.

Sure, you can write unit tests for each member being there making refactoring of any sort a major PIB. Would this be productive? not really.

But, for what it's worth, you just need a little more reflection magic and voila:

    [TestMethod]
    public void PrivateListCanHaveObjectsAdded()
    {
      var target = new A();

      var b = typeof(A).GetNestedType("B", BindingFlags.NonPublic);
      var list = typeof(A).GetField("list", BindingFlags.Instance | BindingFlags.NonPublic);

      var bInstance = Activator.CreateInstance(b);
      var addMethod = typeof(List<>).MakeGenericType(b).GetMethod("Add");
      var countProperty = typeof(List<>).MakeGenericType(b).GetProperty("Count");
      addMethod.Invoke(list.GetValue(target), new object[] { bInstance });

      Assert.AreEqual(1, countProperty.GetValue(list.GetValue(target)));
    }

Upvotes: 2

Alexander
Alexander

Reputation: 63271

Unit tests are meant to test ... units. They're not meant to test the nitty-gritty private internal workings of your program. They're intended to test the public facing API of your classes.

If the public methods of your classes work, then you know any private mechanisms they depend on also work. If the private mechanisms break, they'll cause a public method to stop working.

Upvotes: 3

Related Questions