Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# "internal" access modifier when doing unit testing

I'm new to unit testing and I'm trying to figure out if I should start using more of internal access modifier. I know that if we use internal and set the assembly variable InternalsVisibleTo, we can test functions that we don't want to declare public from the testing project. This makes me think that I should just always use internal because at least each project (should?) have its own testing project. Can you guys tell me why I shouldn't do this? When should I use private?

like image 716
Hertanto Lie Avatar asked Dec 11 '08 01:12

Hertanto Lie


People also ask

Bahasa C digunakan untuk apa?

Meskipun C dibuat untuk memprogram sistem dan jaringan komputer namun bahasa ini juga sering digunakan dalam mengembangkan software aplikasi. C juga banyak dipakai oleh berbagai jenis platform sistem operasi dan arsitektur komputer, bahkan terdapat beberepa compiler yang sangat populer telah tersedia.

Apa yang dimaksud dengan huruf C?

C adalah huruf ketiga dalam alfabet Latin. Dalam bahasa Indonesia, huruf ini disebut ce (dibaca [tʃe]).


2 Answers

Internal classes need to be tested and there is an assembly attribute:

using System.Runtime.CompilerServices;  [assembly:InternalsVisibleTo("MyTests")] 

Add this to the project info file, e.g. Properties\AssemblyInfo.cs, for the project under test. In this case "MyTests" is the test project.

like image 163
EricSchaefer Avatar answered Sep 26 '22 22:09

EricSchaefer


If you want to test private methods, have a look at PrivateObject and PrivateType in the Microsoft.VisualStudio.TestTools.UnitTesting namespace. They offer easy to use wrappers around the necessary reflection code.

Docs: PrivateType, PrivateObject

For VS2017 & 2019, you can find these by downloading the MSTest.TestFramework nuget

like image 45
Brian Rasmussen Avatar answered Sep 23 '22 22:09

Brian Rasmussen