Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reasons for/against using partial classes for testing?

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?

like image 962
grady Avatar asked Sep 10 '26 16:09

grady


2 Answers

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).

like image 73
Jon Skeet Avatar answered Sep 12 '26 10:09

Jon Skeet


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".

like image 23
Dan Bryant Avatar answered Sep 12 '26 09:09

Dan Bryant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!