I got the following error when running the test code. How to workaround the issue? I’m using Visual studio 2010 Premium’s built-in MStest.
Test method TestProgram.myProgramTest.GetTypeListTest threw exception: System.InvalidCastException: Unable to cast object of type 'System.Collections.Generic.List`1[MyProgram.MyClass]' to type 'System.Collections.Generic.List`1[MyProgram.MyClass_Accessor]'.
Method to be tested:
public class MyProjectClass {
private List<MyClass> GetTypeList()
{ ....
}
}
class MyClass {....} // A POCO class
Test code (Most of the code is automatically generated by Visual studio):
[TestMethod()]
[DeploymentItem("myProgram.exe")]
public void GetTypeListTest()
{
MyProjFile_Accessor target = new MyProjFile_Accessor ();
var actual = target.GetTypeList();
Assert.IsTrue(actual.Count > 2);
}
I really don’t know why this question has been down voted twice, all other code is either irrelevant to the issue or automatically generated by Visual studio
It’s pretty straight forward class definition. And the test fixture was created using VS 2010 wizard. The method just return MyClass can pass the test. The problem is the method with return type of List<MyClass>.
Class
MyClasshas no access modifier and C# usesinternalaccess modifier by default.Internal means that class is accessible only inside its assembly.
Unit tests usually implemented in separate assembly and cannot use
MyClass.MS Tests generated
MyClass_Accessorclass that is essentially a wrapper that uses reflection to provide access to class itself as well as its methods.Change declaration to
public class MyClass {....}and re-generate unit test (this is necessary to tell MS Test that_Accessorclass is not necessary).