How to create custom statements in C # / VS?

I ran into an error in some code that extracts metadata from some text and puts it in a dictionary.

My test was unsuccessful when I compared two dictionary objects because the keys were in a different order. I don't care what order the keys are in.

I would like to have an assert method available, for example:

Assert.AreEquivalent(propsExpected,propsActual)

It will look like this:

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

What is the best way to do this?

+3
source share
7 answers

The trick here is to use the new .Net 3.5 feature called extension methods

, Assert 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]);
        }
    }
}

:

Assert.AreEquivalent(propsExpected,propsActual);
-3

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, , .

EDIT: 2 , .
.. Except, , .

+1

NUnit , Is.EquivalentTo(). , , .

CollectionEquivalentConstraint NUnit, , - ?

+1

@Sprintstar @Michael La Voie, Assert - , , , , . 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
    }
}

unit test.

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

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

, case unit test ( ).

0

(, MS, ) - , That.

:

Assert.That.AreEquivalent(propsExpected,propsActual);
0

Source: https://habr.com/ru/post/1709451/


All Articles