Reputation: 437
In relation to this question I asked earlier, I am stuck yet again with my unit test.
My current problem is in relation to testing the protected
methods of my abstract Component
class.
I've successfully implemented a mock class, named ConcreteComponent
, which does its job very well of inheriting everything the abstract class has.
Thing is, I made this concrete class inside my unit test file. The only way of testing protected methods is to have a Private Accessor. However, I cannot create a Private Accessor inside the same file as where the unit test is, and thus, cannot access the protected methods.
I've tried to place the mock concrete class in a separate file, under a different namespace, and this now allows me to create a Private Accessor to which the unit test file can now use. It worked nicely, but then I figured I need this mock concrete class inside the same file where the unit test is.
So now I have two questions:
1) What are the possible workarounds for this problem?
2) Why can't I create a private accessor for a mock class which is inside the same file and namespace as the unit test class?
Upvotes: 3
Views: 3706
Reputation: 5374
You can take a look at PrivateObject class to gain access to non-public API of your class in your tests. It uses reflection internally. Protected assets of a class are still api to an external client which in this case is a sub or derived class. So desire to test such api is understandable. I would not recommend polluting a class to expose public api just for the sake of testing protected api. However, since in your case the derived class is in a test project, you can actually provide public api to make testing easier and improve the performance (reflection will be slower and if you are running tests, continuous testing, as you make code changes, it may make test runs slower depending on the number of test etc.).
Upvotes: 2
Reputation: 17556
Protected functionality is there because you do not want to expose it to your client. But If it is protected then may be accessed through the public interface via some satisfying condition if it is not then it is a dead code so remove it.
so the golden rule is
1- Do not try to circumvent testing private / protected methods by using technology (Reflection etc), try to unit test private / protected through the public interface and BTW why your are using VS 2008 Test and why not NUnit instead
Upvotes: 0