How can I access protected members of a base class during a unit test?

I am creating a unit test in mstest with rhino legs. I have a class A that inherits from class B. I am testing class A and creating an instance for my test. The class that it inherits, β€œB,” has some protected methods and protected properties that I would like to get for my tests. For example, make sure that the protected property in my base class has the expected value.

Any ideas on how I can access these protected class B properties during my test?

+4
source share
3 answers

This is the wrong approach in terms of unit testing. You should only check the open interface and make sure that it behaves as expected, you do not need implementation details such as private / protected. Thus, there is either:

  • The methods / properties that you intend to test must be publicly available OR
  • your test case / concrete test implementation is incorrect.

EDIT:

Sometimes when writing unit tests for outdated code that you cannot change, you can access protected members, in which case the solution may create a wrapper that provides an internal / public property / method for accessing the protected.

And interestingly, you noted the TDD question, try to imagine how you can get access to implementation details in unit tests when you are not yet implemented? Here's how TDD works - you have the interfaces and start writing unit tests before you run.

+6
source

Your protected properties must influence some aspect of your class’s social behavior.

Check out this public behavior.

As for your tests, the inner workings of the class should be a black box. This will give you the freedom to refactor without having to bother with your tests. The only important thing is that they disclose public material, and this is what needs to be checked.

+2
source

In addition, other answers point in the right direction, if you really need to test as you described, do the following:

Create a TestA class that inherits from A. Use this to make protected properties of B public to 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 the syntax of MsTest, but something like this:

 [Test] public void TestThatNameWasSet() { TestA systemUnderTest = new TestA(); systemUnderTest.DoSomething(" new name "); Assert.That(systemUnderTest.GetName(), Is.EqualTo("new name"); } 
+2
source

Source: https://habr.com/ru/post/1383397/


All Articles