Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 352
amateur Avatar asked Nov 28 '11 09:11

amateur


1 Answers

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.

like image 122
sll Avatar answered Sep 22 '22 17:09

sll