简体   繁体   English

无法将List`1 [MyClass]'强制转换为List`1 [MyClass_Accessor]'类型?

[英]Cannot cast List`1[MyClass]' to type List`1[MyClass_Accessor]'?

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. 我正在使用Visual Studio 2010 Premium的内置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): 测试代码(大多数代码由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 我真的不知道为什么这个问题被否决了两次,所有其他代码要么与问题无关,要么由Visual Studio自动生成
It's pretty straight forward class definition. 这是非常简单的类定义。 And the test fixture was created using VS 2010 wizard. 测试夹具是使用VS 2010向导创建的。 The method just return MyClass can pass the test. 只需返回MyClass的方法即可通过测试。 The problem is the method with return type of List<MyClass> . 问题是返回类型为List<MyClass>

Class MyClass has no access modifier and C# uses internal access modifier by default. MyClass类没有访问修饰符,默认情况下C#使用internal访问修饰符。

Internal means that class is accessible only inside its assembly. 内部意味着该类只能在其程序集中访问。

Unit tests usually implemented in separate assembly and cannot use MyClass . 单元测试通常在单独的程序集中实现,不能使用MyClass

MS Tests generated MyClass_Accessor class that is essentially a wrapper that uses reflection to provide access to class itself as well as its methods. MS Tests生成的MyClass_Accessor类实际上是一个包装,该包装使用反射提供对类本身及其方法的访问。

Change declaration to public class MyClass {....} and re-generate unit test (this is necessary to tell MS Test that _Accessor class is not necessary). 将声明更改为public class MyClass {....}然后重新生成单元测试(这是告诉MS Test _Accessor类的必要步骤)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM