views:

18

answers:

0

Hi,

My question is related to trying to understand the reason for the PrivateObject that VS automatically puts in the test and then uses to initialize the constructor for the generated accessor for the class with the private/internal property/method you are unit testing.

Let me show you what I'm talking about...

Imagine this simple class:

class SomeClass
{
    int x;
    int y;

    public SomeClass(int x, int y)
    {
        this.x = x;
        this.y = y;
    }

    private int Sum()
    {
        return x + y;
    }
}

Imagine I want to test the Sum method. I right-click in VS and choose Create Unit Tests and then click OK in the dialog window that pops up. VS then asks me about Adding InternalsVisibleTo attribute to the project I'm testing, I say yes.

In the test project VS just generated for me I get this test:

    [TestMethod()]
    [DeploymentItem("UTTest.exe")]
    public void SumTest()
    {
        PrivateObject param0 = null; // TODO: Initialize to an appropriate value
        SomeClass_Accessor target = new SomeClass_Accessor(param0); // TODO: Initialize to an appropriate value
        int expected = 0; // TODO: Initialize to an appropriate value
        int actual;
        actual = target.Sum();
        Assert.AreEqual(expected, actual);
        Assert.Inconclusive("Verify the correctness of this test method.");
    }

If I want to stick with the generated code I would do this:

    [TestMethod()]
    [DeploymentItem("UTTest.exe")]
    public void SumTest()
    {
        int x = 4;
        int y = 6;
        PrivateObject param0 = new PrivateObject(new SomeClass(x, y));
        SomeClass_Accessor target = new SomeClass_Accessor(param0);
        int expected = 10;
        int actual;
        actual = target.Sum();
        Assert.AreEqual(expected, actual);            
    }

I used the PrivateObject to initialize SomeClass_Accessor. But VS also automatically generates a constructor for SomeClass_Accessor that has the same signature than the constructor of the class the accesor is "accessing", so I can write this test instead:

    [TestMethod()]
    [DeploymentItem("UTTest.exe")]
    public void SumTest()
    {
        int x = 4;
        int y = 6;
        SomeClass_Accessor target = new SomeClass_Accessor(x, y);
        int expected = 10;
        int actual;
        actual = target.Sum();
        Assert.AreEqual(expected, actual);            
    }

So, there's no need for that PrivateObject, at least in this very simple example.

Because the code VS automatically generates has that code with the PrivateObject I would really like to know when it is indispensable, and since VS puts it there by default, it should be the common case and not the exception, and that's why I think I maybe missing something here.

Can anyone shed some light on this for me?

Thanks, Rui