After you added the test project, you need to Add Reference for your project which has the object to be tested. Note if the attributes of the object you want to test are set as Internal, when you are trying to reference your object to test, system will promot following error:
'MyTest' is inaccessible due to its protection level
You need a special trick because your test project can't see the internal attribute of another project.
using System.Runtime.CompilerServices;
[assembly:InternalsVisibleTo("MyTests")]
Add the last one to the project info file, e.g. Properties\AssemblyInfo.cs,
for the project which has the object you want to test, while the "MyTests" is the name of your unit test project assembly. You can find your unit test project assembly name inside your unit test project info file, namely, AssemblyInfo.cs.Note if you still experienced the error of "inaccessible due to protection level", you need to check the test project properties, in most cases, the project assembly name is different than what you thought.
Now your unit test project can see the object to be tested.
Note if you still get
You can add
Note if you want to test the private methods or attributes of your testing object, please use following:using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using YourApplicationToTest; namespace YourTest { [TestClass] public class UnitTestl { [TestMethod] public void TestMethodl() { YourClassToTest ct= new YourClassToTest(); Assert.AreEqual( ct.Name, "I need test!" ); } } }
For test the private static attributes of your object, use following:Class target = new Class(); PrivateObject obj = new PrivateObject(target); var retVal = obj.Invoke("PrivateMethod"); Assert.AreEqual((int)obj.GetField("PrivateAttribute"), 0); Assert.AreEqual(retVal, expectedVal);
UNIT TESTING in Asp.Net: Complete TutorialPrivateType myType = new PrivateType(typeof(MyStaticClass)); myType.SetStaticFieldOrProperty("isMyTypeAttribute", false);
C# “internal” access modifier when doing unit testing
InternalsVisibleTo attribute isn't working
Unit testing private methods in C#
InternalsVisibleToAttribute Class
How to access a Static Class Private fields to unit test its methods using Microsoft Fakes in C#
Unit testing in C# of private-static method accepting other private-static method as a delegate parameter
No comments:
Post a Comment