amateur
amateur

Reputation: 44645

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

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?

Upvotes: 6

Views: 6139

Answers (3)

sll
sll

Reputation: 62544

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.

Upvotes: 7

okrumnow
okrumnow

Reputation: 2416

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");
}

Upvotes: 3

Mongus Pong
Mongus Pong

Reputation: 11477

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.

Upvotes: 2

Related Questions