3

what are pros and cons of using partial classes for writing NUnit tests?

I am going to start:

pro: private methods can be tested
con: TDD is not really possible anymore

What else?

grady
  • 12,281
  • 28
  • 71
  • 110

2 Answers2

6

Con: either you have to test a different build to the one you ship, or you end up with your unit test code (and members) in your shipping code.

Sounds like a really bad idea to me in general.

I usually go for separate production/test projects, with [InternalsVisibleTo] allowing testing of internal methods (which goes against the dogma of some folks, but seems pragmatic to me).

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • +1 for a clear explanation of the problem and a good potential solution. – Dan Nov 09 '10 at 16:03
  • 1
    @grady: If you're using #ifdef to exclude code on compilation, you're still going to be testing a different build to what you ship. – Jon Skeet Nov 09 '10 at 18:34
2

I would argue that being able to test private methods is a 'con', as it can encourage accretion of new code within an existing class. If the private logic is so complex that it needs dedicated tests (beyond what's publicly accessible), then there's a lot of value in pulling out that logic as a separate class with a publicly testable interface. For borderline cases, I cautiously agree with Jon's approach of using internal methods (just be careful how much the internals expose.)

That said, I've occasionally made a class unsealed specifically so that I could write tests that used virtual method calls for sensing of effects, which is loosely related to the partial class approach. This always feels a bit dirty to me and I sometimes wished there were a way to mark a class as "internal unsealed".

Dan Bryant
  • 27,329
  • 4
  • 56
  • 102