unit tests - white box vs. black box strategies

779 Views Asked by At

I found, that when I writing unit tests, especially for methods who do not return the value, I mostly write tests in white box testing manner. I could use reflection to read private data to check is it in the proper state after method execution, etc...

this approach has a lot of limitation, most important of which is

  1. You need to change your tests if you rework method, even is API stay the same
  2. It's wrong from information hiding (encapsulation) point of view - tests is a good documentation for our code, so person who will read it could get some unnecessary info about implementation

But, if method do not return a value and operate with private data, so it's start's very hard (almost impossible) to test like with a black-box testing paradigm.

So, any ideas for a good solution in that problem?

2

There are 2 best solutions below

0
ale On

I could use reflection to read private data to check is it in the proper state after method execution

This can really be a great problem for maintenance of your test suite

in .Net instead you could use internal access modifier, so you could use the InternalsVisibleToAttribute in your class library to make your internal types visible to your unit test project.

The internal keyword is an access modifier for types and type members. Internal types or members are accessible only within files in the same assembly

This will not resolve every testing difficulty, but can help

Reference

3
Bob Dalgleish On

White box testing means that you necessarily have to pull some of the wiring out on the table to hook up your instruments. Stuff I've found helpful:

1) One monolithic sequence of code, that I inherited and didn't want to rewrite, I was able to instrument by putting a state class variable into, and then setting the state as each step passed. Then I tested with different data and matched up the expected state with the actual state.

2) Create mocks for any method calls of your method under test. Check to see that the mock was called as expected.

3) Make needed properties into protected instead of private, and create a sub-class that I actually tested. The sub-class allowed me to inspect the state.