C# 如何对私有列表进行单元测试/如何将对象强制转换为列表 公共类1 { 私人名单; 公共类别1() { 列表=新列表(); } 私有addSomethingToList(字符串) { //在列表中添加一些内容 } } [测试类] 公共类DoSomethingToListTests { [测试方法] 公共空间是什么东西 { string1=“某物”; PrivateObject prob=新的PrivateObject(新的Class1()); 对象[]arg={string1}; prob.Invoke(“addSomethingToList”,string1); 预期列表=新列表(); 预期。添加(“某物”); 对象实际值=prob.GetField(“列表”); 收款资产等于(预期、实际); } }
这给了我 参数2:无法从“对象”转换为System.Collections.ICollection 论点2是实际的 及 与“Microsoft.VisualStudio.TestTools.UnitTesting.CollectionAssert.AreEqual(System.Collections.ICollection,System.Collections.ICollection)”匹配的最佳重载方法具有一些无效参数 问题在于,它将预期作为列表进行评估,而实际作为对象进行评估 有没有办法让它成为一张清单 我试过了C# 如何对私有列表进行单元测试/如何将对象强制转换为列表 公共类1 { 私人名单; 公共类别1() { 列表=新列表(); } 私有addSomethingToList(字符串) { //在列表中添加一些内容 } } [测试类] 公共类DoSomethingToListTests { [测试方法] 公共空间是什么东西 { string1=“某物”; PrivateObject prob=新的PrivateObject(新的Class1()); 对象[]arg={string1}; prob.Invoke(“addSomethingToList”,string1); 预期列表=新列表(); 预期。添加(“某物”); 对象实际值=prob.GetField(“列表”); 收款资产等于(预期、实际); } },c#,list,unit-testing,object,casting,C#,List,Unit Testing,Object,Casting,这给了我 参数2:无法从“对象”转换为System.Collections.ICollection 论点2是实际的 及 与“Microsoft.VisualStudio.TestTools.UnitTesting.CollectionAssert.AreEqual(System.Collections.ICollection,System.Collections.ICollection)”匹配的最佳重载方法具有一些无效参数 问题在于,它将预期作为列表进行评估,而实际作为对象进行评估 有没有办法让
public class Class1
{
private List<string> list;
public Class1()
{
list = new List<string>();
}
private addSomethingToList(string something)
{
// add something to the list
}
}
[TestClass]
public class DoSomethingToListTests
{
[TestMethod]
public void DoSomethingToList_Something()
{
string string1 = "something";
PrivateObject prob = new PrivateObject(new Class1());
object[] arg = { string1 };
prob.Invoke("addSomethingToList", string1);
List<string> expected = new List<string>();
expected.Add("something");
object actual = prob.GetField("list");
CollectionAssert.AreEqual(expected, actual);
}
}
List-actual=prob.GetField(“List”);
但这给了我一个错误
无法将类型“object”隐式转换为“System.Collections.Generic.List”。存在显式转换(是否缺少强制转换?)
您可以创建一个新的项目列表,其中填充了实际的
List<string/object> actual = prob.GetField("list");
var actualist=new List(){actual};
集合资产等于(预期、实际);
另一个我不理解的错误-集合初始值设定项的最佳重载Add方法System.Collections.Generic.List.Add(string)’有一些无效参数。我将其更改为new List,它可以工作。但是,当运行测试时,我得到的结果消息是:CollectionAssert.AreEqual失败。(索引0处的元素不匹配。)这很奇怪,因为它们完全相同。您可以覆盖相等比较器,它是CollectionAssert.Areequal中的第三个参数。您将如何做到这一点?创建一个实现IComparer的类,然后在第三个参数中新建它,例如new StringComparer()等等。我可能可以用一种公开的方法来获取列表,但我更想知道如何用另一种方法。你这么做是因为你想测试私有函数吗?@Magnus是的,我不理解人们不喜欢测试私有函数。另一种方法是将它们设置为内部函数,并使内部方法对测试项目可见。是的。我决定公开这个方法,因为不管怎样,获取列表在以后可能会很有用
var actualList = new List<string>() { actual };
CollectionAssert.AreEqual(expected, actualList );