Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.Net core library: How to test private methods using xUnit

Tags:

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?

like image 498
Perez Lamed van Niekerk Avatar asked Jan 04 '17 11:01

Perez Lamed van Niekerk


People also ask

How do I unit test private methods in xUnit?

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.

Should I test private methods C#?

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

Can you test private methods?

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.


1 Answers

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")] 
like image 98
Patrick McDonald Avatar answered Sep 20 '22 13:09

Patrick McDonald