2009-05-30 51 views
3

我遇到了一些代码中的错误,它从一些文本中提取元数据并将其放入字典中。如何在C#/ VS中构建自定义断言?

当我比较两个字典对象时,我的测试失败了,因为按键顺序不同。我真的不关心什么顺序键在

我想有可用的断言方法,如:。

Assert.AreEquivalent(propsExpected,propsActual) 

这将评估,如:

Assert.AreEqual(propsExpected.Count, propsActual.Count); 
foreach (var key in propsExpected.Keys) 
{ 
    Assert.IsNotNull(props[key]); 
    Assert.AreEqual(propsExpected[key], props[key]); 
} 

有什么最好的方法来做到这一点?

回答

-3

这里的技巧是使用的.Net 3.5的新功能叫做extension methods

例如获得断言类,以支持使用您提供的代码AreEquivalent方法上面,你会做这样的事情:

public static class MyAssertExtensions 
{ 
    public static void AreEquivalent(this Assert ast, 
     Dictionary<string, int> propsExpected, 
     Dictionary<string, int> propsActual) 
    { 
     Assert.AreEqual(propsExpected.Count, propsActual.Count); 
     foreach (var key in propsExpected.Keys) 
     { 
      Assert.IsNotNull(props[key]); 
      Assert.AreEqual(propsExpected[key], props[key]); 
     } 
    } 
} 

这样你你c实际上是这样调用断言:

Assert.AreEquivalent(propsExpected,propsActual); 
+0

这里的问题是,如果在两个词典中的元素不具有相同的顺序,断言将失败,即使元素是等于 – 2009-05-31 01:04:35

1

如果你能使用LINQ,


void Main() 
{ 
    Dictionary d1 = new Dictionary<int, string>(); 
    Dictionary d2 = new Dictionary<int, string>(); 

    d1.Add(1, "1"); 
    d1.Add(2, "2"); 
    d1.Add(3, "3"); 

    d2.Add(2, "2"); 
    d2.Add(1, "1"); 
    d2.Add(3, "3"); 

    Console.WriteLine(d1.Keys.Except(d2.Keys).ToArray().Length); 
} 
 

这将打印0到控制台。除了试图在上面的例子中找出两个列表之间的区别。

您可以将其与0进行比较以查找是否有任何区别。

编辑:你可以在做这个之前添加检查比较2个字典的长度。
即,如果长度不同,您可以使用除外,只有

1

使用NUnit,可以使用Is.EquivalentTo()约束来比较两个集合。此约束将评估集合并检查集合是否具有相同的元素,但它不关心订单。

Documentation for CollectionEquivalentConstraint 如果您不使用NUnit,那么您使用的测试框架中可能存在类似的东西?

0

至于@Sprintstar在为香格里拉@迈克尔Vo1E时的回答评论中指出,断言类不能因为它是静态的伸展自然,我解决这个问题的方式通常是通过创建一个包含我的定制方法的测试库,其中包含多个断言和其他验证方法。For ex-

public static class MyTestRepository 
{ 
    public static void ArePropsEquivalent(
     Dictionary<string, int> propsExpected, 
     Dictionary<string, int> propsActual) 
    { 
     //Multiple Asserts and validation logic 
     //required for Equivalence goes here 
    } 

    public static void ArePropsSimilar(
     Dictionary<string, int> propsExpected, 
     Dictionary<string, int> propsActual) 
    { 
     //Multiple Asserts and validation logic 
     //required for similarity goes here 
    } 
} 

然后我从单元测试方法中调用这些方法。

[TestMethod] 
public void TestMthod1() 
{ 
    //Props declaration goes here 
    MyTestRepository.ArePropsEquivalent(propsExpected, propsActual); 
} 

[TestMethod] 
public void TestMthod2() 
{ 
    //Props declaration goes here 
    MyTestRepository.ArePropsSimilar(propsExpected, propsActual); 
} 

这样我可以少写,并在实际的单元测试用例的方法做多,并保持它的模块化(不同型号的情况下)。