I am currently playing around with the latest Visual Studio 2017 Release Candidate by creating a .Net Standard 1.6 library. I am using xUnit to unit test my code and was wondering if you can still testing internal methods in VS2017.
I remember that you could all a line AssemblyInfo.cs class in VS2015 that would enable specified projects to see internal methods
[assembly:InternalsVisibleTo("MyTests")]
As there is no AssemblyInfo.cs class in VS2017 .Net Standard projects I was wondering if you can still unit test internal methods?
According to .NET docs for the InternalsVisibleToAttribute
:
The attribute is applied at the assembly level. This means that it can be included at the beginning of a source code file, or it can be included in the AssemblyInfo file in a Visual Studio project.
In other words, you can simply place it in your own arbitrarily named .cs file, and it should work fine:
// some .cs file included in your project
using System.Runtime.CompilerServices;
[assembly:InternalsVisibleTo("MyTests")]
While the first answer is perfectly fine. If you feel you still want to do this in the original AssemblyInfo
you can always choose to not auto generate the file and add it manually.
<PropertyGroup>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
</PropertyGroup>
For more information: https://stackoverflow.com/a/47075759/869033
The "InternalsVisibleTo" attribute is key to any sort of "white-box" (the term of the decade, I guess) testing for .Net. It can be placed in any c# file with the "assembly" attribute on the front. Note that MS DOCs say that the assembly name must be qualified by the public key token, if it is signed. Sometimes that does not work and one must use the full public key in it's place. Access to internals is key to testing concurrent systems and in many other situations. See https://www.amazon.com/xUnit-Test-Patterns-Refactoring-Code/dp/0131495054. In this book, Meszaros describes a variety of coding styles that basically constitute a "Design For Test" approach to program development. At least that's the way I've used it over the years.
Another way is to use a 'wrapper' TestMyFoo public class inside the target project that has public methods and inherets from the class you need to test (e.g. MyFoo). These public methods simply call through onto the base class you want to test.
It is not 'ideal' as you end up shipping a test hook in your target project. But consider modern reliable cars ship with diagnostic ports and modern reliable electronics ship with a JTAG connection. But nobody is silly enough to drive their car using the diagnostic port.
来源:https://stackoverflow.com/questions/42235401/unit-testing-internal-methods-in-vs2017-net-standard-library