Integration testing private classes and methods

2019-05-24 13:59发布

问题:

For unit testing you shouldn't test private methods, yes, but for integration tests (using a unit testing framework like MSTest or NUnit) I would very much like to run the internal API calls against a test url, to make sure the current code works when the third party API vendor changes their backend.

Given the complexity of the system (stupid API's have hundreds of parameters) I have hidden most of it behind interfaces and IoC, with the API helper class completely internal to our data layer library. I don't want to change this because it used to be public and we found the odd developer new to the project and inexperienced in general would promptly go ahead and call the api directly from website code. Making the class internal should ensure that they at least think before destroying the point of our abstraction layer.

I've been building up a mass of reflection code to get at the internal methods, but it is not working too well and is getting sphagetti-ish. Is there a way to make the methods publically visible for certain libraries? Is there a way to get the test libray to treat itself as part of the library containing the api? Is any of this best practice?

回答1:

The InternalsVisibleTo attribute is your friend here =) If you place it in the AssemblyInfo.cs (at least that's where I usually put it) and specify the name(s) of the test/other assemblies you wish to expose internal methods to, they're then available. The added bonus (at least to my mind), is that Visual Studio's intellisense system / compiler is aware of the attribute and its purpose and you'll have full intellisense provided for the internal methods.

And unlike reflection it won't break horribly without providing a compile-time error whenever you change the internal methods signature.