how can protected members of base class be accessed during unit test?
Asked Answered
T

3

6

I am creating a unit test in mstest with rhino mocks. I have a class A that inherits class B. I am testing class A and create an instance of it for my test. The class it inherits, "B", has some protected methods and protected properties that I would like to access for the benefit of my tests. For example, validate that a protected property on my base class has the expected value.

Any ideas how I might access these protected properties of class B during my test?

Tented answered 28/11, 2011 at 9:38 Comment(1)
If you need more details regarding how to unit test particular scenario - please share a code you are testingRalleigh
R
7

This is wrong approach from unit testing perspectives. You should test only public interface and ensure that it behaves as expected, you should not care details of implementation like private/protected. So there are either:

  • methods/properties you are going to test really should be public OR
  • your test case/particular test implementation is wrong

EDIT:

Sometimes when writing unit tests for legacy code which you not able to change you could be forced to access protected members, in this case solution could be creating a wrapper which exposes internal/public property/method to access protected one.

Also what interesting, you marked question by TDD tag, try out imagine how you would be able accessing details of implementation in unit tests when you do not have an implementation yet? This is how TDD works - you have an interfaces and start writing unit tests before an implementation done.

Ralleigh answered 28/11, 2011 at 9:46 Comment(0)
S
3

Besides that the other answers point into the right direction, if you really need to test like you described, do this:

Create a class TestA that inherits from A. Use this to make the protected properties of B public for the test. If you have

class B {
    protected string Name {get; set;}
}

class A: B {
    public void DoSomething(string msg) {
        Name = msg.Trim();
    }
}

class TestA: A {
    public string GetName() {
        return Name;
    }
}

In your test, now use TestA. I don't know MsTest syntax, but roughly it is this:

[Test]
public void TestThatNameWasSet() {
    TestA systemUnderTest = new TestA();
    systemUnderTest.DoSomething("  new name  ");
    Assert.That(systemUnderTest.GetName(), Is.EqualTo("new name");
}
Sellma answered 28/11, 2011 at 9:56 Comment(0)
S
2

Your protected properties should affect some aspect of the public behaviour of your class.

Test this public behaviour.

As far as your tests are concerned the internal workings of the class should be a black box. This will give you the freedom to refactor without having to mess with your tests. The only important thing is what public stuff they expose and this is what should be tested.

Skuld answered 28/11, 2011 at 9:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.