The latest xunit framework does not allow test runners in library code when compiled with .Net Core framework (this is allowed for normal Visual Studio code). The solution is to create a separate testing project to run your test cases.
The problem that I am having is that some methods that I want to test are 'private' methods. How can I call those methods from my test project without making their scope 'public'?
The more general question is: How do you test private methods when the public method that uses the private method can not be used? (because of its interactive nature - that is, it has a ReadLine(); contained in it)
Possible solutions:
1) Make the private methods public and rename them in a manner to indicate that they should not be used externally. (Use 'private' or 'internal' as part of the name)
2) Create a ' public static bool Testflag' field that can be set to true in order to bypass the interactive parts of the public method to ensure testing of all its parts.
(Although I have used both of the above methods - I really do not like it because private methods should stay private and flags add a lot of extra complexities. Has someone encountered the same problem? How did you solved it?
A quick solution is to make private members that you want to test internal . You can then add an InternalsVisibleTo attribute to your main library's AssemblyInfo. cs. This will allow your test library (and no other library, without reflection) access to the internal methods/classes in your main library.
"If we need to test a private method, we should make it public. If making it public bothers us, in most cases, it means that our class is doing too much and we ought to fix it." The way to fix it, according to the author, is by creating a new class and adding the method as public .
The short answer is that you shouldn't test private methods directly, but only their effects on the public methods that call them. Unit tests are clients of the object under test, much like the other classes in the code that are dependent on the object.
A quick solution is to make private
members that you want to test internal
.
You can then add an InternalsVisibleTo
attribute to your main library's AssemblyInfo.cs. This will allow your test library (and no other library, without reflection) access to the internal methods/classes in your main library.
e.g.
[assembly: InternalsVisibleTo("Library.Tests")]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With