1

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?

Ph0en1x
  • 9,943
  • 8
  • 48
  • 97

2 Answers2

2

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.

Bob Dalgleish
  • 8,167
  • 4
  • 32
  • 42
  • Mocking is a good option indeed, but makes things a bit complex I think. – Ph0en1x Apr 16 '14 at 19:16
  • Compared to what I had to do in my first example, I would prefer to introduce mocks. Your very first mock is the most expensive; after that, it becomes easier and more productive. – Bob Dalgleish Apr 16 '14 at 19:21
  • Mark Seemann [describes a good approach](http://blog.ploeh.dk/2013/10/23/mocks-for-commands-stubs-for-queries/ "Mock commands; Query stubs") to use for determining when to use a mock. This helps in mitigating the number of implementation details that can make their way into tests. – Lilshieste Apr 22 '14 at 04:41
0

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

ale
  • 10,012
  • 5
  • 40
  • 49