Search code examples
c#unit-testingvs-unit-testing-framework

VisualStudio - How do i automatically create accessors for base class functions when base class is in another assembly?


I have the following setup. A solution with 3 Projects.

Project A, Namespace A, Class A

Project B, Namespace B, Class B : A

and a Test project for unit tests on B. To access private functions of B i create an accessor in my Test project using Create Private Accessor -> Test.

It seems as A is in another assembly VS does not create accessor functions for A.


Solution

  • You need to use multiple accessors. Consider this:

    // Assembly A
    public class ClassA
    {
        protected int someInt = 1;
        private void DoSthmWithA()
        {
            someInt = 10;
        }
    }
    
    // Assembly B
    public class ClassB : ClassA
    {
        private void DoSthmWithB()
        {
            someInt = 11;
        }
    }
    
    [TestMethod()]
    public void Testing
    {
        var target = new ClassB();
    
        var poA = new PrivateObject(target, new PrivateType(typeof (ClassA)));
        var poB = new PrivateObject(target);
    
        var accA = new ClassA_Accessor(poA);
        var accB = new ClassB_Accessor(poB);
        accA.DoSthmWithA();
        Assert.AreEqual(accA.someInt, 10);
        accB.DoSthmWithB();
        Assert.AreEqual(accA.someInt, 11);
    }
    

    or

    [TestMethod()]
    public void Testing
    {
       var target = new ClassB();
    
       var poA = new PrivateObject(target, new PrivateType(typeof(ClassA)));
       var poB = new PrivateObject(target);
    
       poA.Invoke("DoSthmWithA");
    
       var accA = new ClassA_Accessor(poA);
       Assert.AreEqual(accA.someInt, 10);
    
       poB.Invoke("DoSthmWithB");
    
       Assert.AreEqual(accA.someInt, 11);
    }