Assert statements

The assert statement is used for comparing the result from the original method with the expected result, and then passing or failing the test based on the match. Whatever the result produced by the method may be, the end result of the test method depends on the return value of the assert method. The assert statement takes care of setting the result. There are multiple overloaded methods supported by the Assert statement to set the return value to Pass or Fail or Inconclusive. If the assert statement is not present in the test method, the test method will always return a Pass value. If there are many assert statements in the test method, the test will be in Pass state until one of the assert statements returns Fail.

In the preceding example, the test method CalculateTotalPriceTest has two assert statements Assert.AreEqual and Assert.Inconclusive. The Assert.AreEqual statement has two parameters, one called expected, which is the expected value returned by the CalculateTotalPrice method. The second parameter actual is the actual value returned by the method. The Assert.AreEqual statement, which is explained in detail in the next section, compares these two values and returns the Test Result as Pass if both the values match. It returns Fail if there is a mismatch between these two values.

        [TestMethod()]
        public void CalculateTotalPriceTest()
        {
            Class1 cls = new Class1(); // TODO: Initialize to an //appropriate value
            double quantity = 0F; // TODO: Initialize to an //appropriate value
            double expected = 0F; // TODO: Initialize to an 
                                 //appropriate value
            double actual;
            actual = cls.CalculateTotalPrice(quantity);
            Assert.AreEqual(expected, actual);
            Assert.Inconclusive("Verify the correctness of this test 
                                 method.");
        }

The test method also contains the Assert.Inconclusive statement to return the result as Inconclusive if the test method is not complete. Remove this line if the code is complete and returns the result. If the above code is running without setting the value for the variables quantity and expected, the return would be Inconclusive. Now set the value for quantity and expected as:

double quantity = 10F;
double expected = 159F;

The returned result would be a Fail value because the actual value returned by the method would be 160, while our expected value is 159. If you change the expected value to 160 then the test would pass. The examples have shown only one Assert type so far. There are many other asserts statements provided by the Visual Studio unit test framework to support and do a complete unit test for various scenarios.

Types of Asserts

The Assert class supports both comparison and conditional testing capabilities. The Microsoft.VisualStudio.TestTools.UnitTesting namespace contains all these assert types. The actual and expected values are compared based on the type of assert used and the result decides the test pass or failure state.

Assert

The assert class has many different overloaded methods for comparing the values. Each method is used for a specific type of comparison. For example, an assert can compare a string with a string, or an object with another object, but not an integer with an object. Overloaded methods are methods with the same name, but with additional or optional parameters added to the method. This is to change the behavior of the method based on the need. For example, the assert method provides an overloaded method to compare the values within a specified accuracy, which is explained in detail when comparing double values.

Consider the following simple Item class shown with three properties each with different data types:

    public class Item {
        public int ItemID { get; set; }
        public string ItemType { get; set; }
        public double ItemPrice { get; set; }
    }

The code shown here is a sample which creates a new Item object with values set for the properties:

        public Item GetObjectToCompare() {
            Item objA = new Item();
            objA.ItemID = 100;
            objA.ItemType = "Electronics";
            objA.ItemPrice = 10.99;
            return objA;
        }

Create a unit test for the above method and set the properties for the object, like in the following code:

        [TestMethod()]
        public void GetObjectToCompareTest()
        {
            Class1 target = new Class1(); 
            Item expected = new Item(); 
            expected.ItemID = 100;
            expected.ItemType = "Electronics";
            expected.ItemPrice = 10.39;
            Item actual;
            actual = target.GetObjectToCompare();
            Assert.AreEqual(expected, actual);

        }

With the above sample code and the unit test, we will look at the results of each overloaded method in the Assert class.

Assert.AreEqual

This is used for comparing and verifying actual and expected values. The following are the overloaded methods for the Assert.AreEqual() method and the result for the previous code samples:

Method

Description

Assert.AreEqual(Object, Object);

Verifies if both the objects are equal.

The test fails because the actual and the expected values are two different objects even though the properties are the same.

Try setting expected = actual just before the assert statement and run the test again; the test would pass as both the objects are now the same.

Assert.AreEqual(Object, Object, String)

Used for verifying two objects and displays the string message if the test fails. For example, if the statement is like this:

Assert.AreEqual(expected, actual, "Objects are Not equal")

The output of the test would be Assert.AreEqual failed. Expected:<TestLibrary.Item>. Actual:<TestLibrary.Item>. Objects are not equal.

Assert.AreEqual(Object, Object, String, Object[])

Used for verifying two objects and displays the string message if the test fails; the formatting is applied to the displayed message. For example, if the assert statement is like this:

Assert.AreEqual(expected, actual, "Objects {0} and {1} are not equal", "ObjA", "ObjB")

The displayed message if the test fails would be Assert.AreEqual failed. Expected:<TestLibrary.Item>. Actual:<TestLibrary.Item>. Objects ObjA and ObjB are not equal.

Assert.AreEqual(String, String, Boolean)

Used for comparing and verifying two strings; the third parameter is to specify whether to ignore case or not. If the assert statement is like this:

Assert.AreEqual(expected.ItemType, actual.ItemType, false)

The test will pass only if both the values are the same including the casing.

Assert.AreEqual(String, String, Boolean, CultureInfo)

Used for comparing two strings specifying casing to include for comparison including the culture info specified; for example, if the assert is like this:

Assert.AreEqual(expected.ItemType, actual.ItemType, false, System.Globalization.CultureInfo.CurrentCulture.EnglishName)

...and the property value for expected.ItemType="electronics", then the result would be:

Assert.AreEqual failed. Expected:<electronics>. Case is different for actual value:<Electronics>. English (United States).

Assert.AreEqual(String, String, Boolean, String)

Used for comparing two strings specifying whether to include casing, display the specified message if the test fails; for example if the statement is like this:

Assert.AreEqual(expected.ItemType, actual.ItemType, false, "Both the strings are not equal")

The Test Result would be Assert.AreEqual failed. Expected:<electronics>. Case is different for actual value:<Electronics>. Both the strings are not equal.

Assert.AreEqual(String, String, Boolean, CultureInfo, String)

Used for comparing two strings specifying casing and culture info to include for comparison; displays the specified message if the test fails; the following is an example:

Assert.AreEqual(expected.ItemType, actual.ItemType, false, System.Globalization.CultureInfo.CurrentCulture.EnglishName, "Both the strings {0} and {1} are not equal", actual.ItemType, expected.ItemType)

Assert.AreEqual(String, String, Boolean, String, Object[])

Used for comparing two strings specifying the casing, the specified message is displayed with the specified formatting applied to it; for example if the statement is like this:

Assert.AreEqual(expected.ItemType, actual.ItemType, false, "Both the strings '{0}' and '{1}' are not equal", actual.ItemType, expected.ItemType);

The Test Result if the test fails would be Assert.AreEqual failed. Expected:<electronics>. Case is different for actual value:<Electronics>. Both the strings 'Electronics' and 'electronics' are not equal.

Assert.AreEqual(String, String, Boolean, CultureInfo, String, Object[])

Used for comparing two strings specifying casing and culture information to include for comparison; displays the specified message if the test fails; the specified formatters are applied to the message to replace it with the parameter values. The following is an example:

Assert.AreEqual(expected.ItemType, actual.ItemType, false, System.Globalization.CultureInfo.CurrentCulture.EnglishName, "Both the strings '{0}' and '{1}' are not equal", actual.ItemType, expected.ItemType);

If the test fails, it displays the message with the formatters {0} and {1} replaced with the values in actual.Itemtype and expected.ItemType.

Assert.AreEqual(Double, Double, Double)

Assert.AreEqual(Double, Double, Double, String)

Assert.AreEqual(Double, Double, Double, String, Object[])

These are the three different overloaded assert methods for comparing and verifying the Double values; the first and second parameter values are the expected and actual values, the third parameter is to specify the accuracy within which the values should be compared. The fourth parameter is for the message and fifth is the format to be applied for the message; for example, if the assert is like this:

Assert.AreEqual(expected.ItemPrice, actual.ItemPrice, 0.5, "The values {0} and {1} does not match within the accuracy", expected.ItemPrice, actual.ItemPrice);

The test would produce a result of: Assert.AreEqual failed. Expected a difference no greater than <0.5> between expected value <10.39> and actual value <10.99>. The value 10.39 and 10.99 does not match within the accuracy. Here the expected accuracy is 0.5 but the difference is 0.6.

Assert.AreEqual(Single, Single, Single)

Assert.AreEqual(Single, Single, Single, String)

Assert.AreEqual(Single, Single, Single, String, Object[])

This is very similar to the Double value comparison shown previously but the values here are of type Single; this method also supports the message and the formatters to be displayed if the test fails.

Assert.AreEqual<T>(T, T,)

Assert.AreEqual<T>(T, T, String)

Assert.AreEqual<T>(T, T, String, Object[])

These overloaded methods are used for comparing and verifying the generic type data; the assertion fails if they are not equal and displays the message by applying the specified formatters; for example, if the assert is like:

Assert.AreEqual<Item>(actual, expected, "The objects '{0}' and '{1}' are not equal", "actual", "expected")

The result if the test fails would be Assert.AreEqual failed. Expected:<TestLibrary.Item>. Actual:<TestLibrary.Item>. The objects 'actual' and 'expected' are not equal.

Assert.AreNotEqual

All the previously mentioned overloaded methods for Assert.AreEqual also applies to Assert.AreNotEqual, the only difference being that the comparison is the exact opposite of the AreEqual assert. For example, the following method verifies if the two strings are not equal by ignoring the casing as specified by Boolean. The test fails if they are equal and the message is displayed with the specified formatting applied to it:

Assert.AreNotEqual(String, String, Boolean, String, Object[])

The following code compares two strings and verifies whether they are equal or not:

Assert.AreNotEqual(expected.ItemType, actual.ItemType, false, "Both the strings '{0}' and '{1}' are equal", expected.ItemType, actual.ItemType);

If the string values are equal, the output of this would be:

Assert.AreNotEqual failed. Expected any value except:<Electronics>. Actual:<Electronics>. Both the strings 'Electronics' and 'Electronics' are equal

Assert.AreSame

The following table shows different types of overloaded assert methods for the assert type AreSame, which checks whether objects are same or not:

Method

Description

Assert.AreSame(Object, Object)

This method compares and verifies whether both the object variables refer to the same object; even if the properties are the same, the objects might be different; for example, the following test will pass because the objects are the same.

List<string> firstLst = new List<string>(3);

List<string> secondLst = firstLst;

Assert.AreSame(firstLst, secondLst);

Both objects A and B refer to the same object and so they are the same.

Assert.AreSame(Object, Object, String)

This method compares and verifies whether both object variables refer to the same object; if not, the message will be displayed; for example, the following code compares the two objects firstLst and secondLst:

List<string> firstLst = new List<string>(3);

List<string> secondLst = new List<string>(5);

Assert.AreSame(firstLst, secondLst, "The objects are not the same");

The test fails with the output Assert.AreSame failed. The objects expected and actual are not the same.

Assert.AreSame(Object, Object, String, Object[])

This method compares and verifies whether both object variables refers to the same object; if not, the message will be displayed with the specified formatting; for example, the following code compares two objects firstLst and secondLst:

List<string> firstLst = new List<string>(3);

List<string> secondLst = new List<string>(5);

Assert.AreSame(firstLst, secondLst, "The objects {0} and {1} are not same", "firstLst", "secondLst");

The test fails with the output Assert.AreSame failed. The objects firstLst and secondLst are not same.

Assert.AreNotSame

This Assert is used to verify that two objects are not the same. The test fails if the objects are the same. The same overloaded methods for Assert.AreSame apply here, but the comparison is the exact opposite. The following are the three overloaded methods applied to Assert.AreNotSame:

  • Assert.AreNotSame(Object, Object)
  • Assert.AreNotSame(Object, Object, String)
  • Assert.AreNotSame(Object, Object, String, Object[])

For example, the following code verifies if objects firstLst and secondLst are not the same. If they are the same, the test fails with the specified error message with the specified formatting applied to it:

List<string> firstLst = new List<string>(5);
List<string> secondLst = firstLst);
Assert.AreNotSame(firstLst, secondLst, "The test fails because the objects {0} and {1} are same", "firstLst", "secondLst");

The above test fails with the message Assert.AreNotSame failed. The test fails because the objects firstLst and secondLst are same.

Assert.Fail

This assert is used for failing the test without checking any condition. Assert.Fail has three overloaded methods:

Method

Description

Assert.Fail()

Fails the test without checking any condition.

Assert.Fail(String)

Fails the test without checking any condition and displays the message.

Assert.Fail(String, Object[])

Fails the test without checking any condition and displays the message with the specified formatting applied to the message; for example, the following code does not check for any condition but fails the test and displays the message:

Assert.Fail("This method '{0}' is set to fail temporarily", "GetItemPrice");

The output for the preceding code would be Assert.Fail failed. This method 'GetItemPrice' is set to fail temporarily.

Assert.Inconclusive

This is useful in case the method is incomplete and cannot determine whether the output is true or false. Set the assertion to be inconclusive until the method is complete for testing. There are three overloaded methods for Assert.Inconclusive:

Method

Description

Assert.Inconclusive()

Assertion cannot be verified; set to inconclusive.

Assert.Inconclusive(String)

Assertion cannot be verified; set to inconclusive and displays the message.

Assert.Inconclusive(String, Object[])

Assertion cannot be verified; set to inconclusive and displays the message with the specified formatting applied to it; for example, the following code sets the assertion as inconclusive which means neither true nor false.

Assert.Inconclusive("This method '{0}' is not yet ready for testing", "GetItemPrice");

The output for the preceding code would be Assert.Inconclusive failed. This method 'GetItemPrice' is not yet ready for testing.

Assert.IsTrue

This is used for verifying if the condition is true. The test fails if the condition is false. There are three overloaded methods for Assert.IsTrue:

Method

Description

Assert.IsTrue()

Used for verifying the condition; test fails if the condition is false.

Assert.IsTrue(String)

Used for verifying the condition and displays the message if the test fails.

Assert.IsTrue(String, Object[])

Verifies the condition and displays the message if the test fails; applies the specified formatting to the message.

For example, the following code fails the test as the conditions return false.

List<string> firstLst = new List<string>(3);

List<string> secondLst = new List<string>(5);

Assert.IsTrue(firstLst == secondLst, "Both {0} and {1} are not equal", "firstLst", "secondLst");

The output message for the preceding test would be Assert.IsTrue failed. Both 'firstLst' and 'secondLst' are not equal.

Assert.IsFalse

This is to verify if the condition is false. The test fails if the condition is true. Similar to Assert.IsTrue, this one has three overloaded methods:

Method

Description

Assert.IsFalse()

Used for verifying the condition; test fails if the condition is true.

Assert.IsFalse(String)

Used for verifying the condition; displays the message if the test fails with the condition true.

Assert.IsFalse(String, Object[])

Verifies the condition and displays the message if the test fails with the condition true and applies the specified formatting to the message.

For example, the following code fails the test as the condition returns true:

List<string> firstLst = new List<string>(3);

List<string> secondLst = firstLst;

Assert.IsFalse(firstLst == secondLst, "Both {0} and {1} are equal", "firstLst", "secondLst");

The output message for the above test would be Assert.IsFalse failed. Both ''firstLst'' and ''secondLst'' are equal

Assert.IsNull

This is used to verify whether an object is null. The test fails if the object is not null. Given here are the three overloaded methods for Assert.IsNull.

Method

Description

Assert.IsNull(Object)

Verify if the object is null.

Assert.IsNull(Object, String)

Verify if the object is null; displays the message if the object is not null and the test fails.

Assert.IsNull(Object, String, Object[])

Verify if the object is null and display the message if the object is not null; apply the formatting to the message.

For example, the following code verifies if the object is null and fails the test if it is not null and displays the formatted message:

List<string> firstLst = new List<string>(3);

List<string> secondLst = firstLst;

Assert.IsNull(secondLst, "Object {0} is not null", "secondLst");

The preceding code fails the test and displays the error message Assert.IsNull failed. Object ''secondLst'' is not null.

Assert.IsNotNull

This is to verify if the object is null or not. The test fails if the object is null. This is the exact opposite of the Assert.IsNull and has the same overloaded methods.

Method

Description

Assert.IsNotNull(Object)

Verifies if the object is not null.

Assert.IsNotNull(Object, String)

Verifies if the object is not null, and displays the message if the object is null and the test fails.

Assert.IsNotNull(Object, String, Object[])

Verifies if the object is not null and displays the message if the object is null; applies the formatting to the message.

For example, the following code verifies if the object is not null and fails the test if it is null and displays the formatted message :

List<string> secondLst = null;

Assert.IsNotNull(secondLst, "Object {0} is null", "secondLst");

The preceding code fails the test and displays the error message Assert.IsNotNull failed. Object 'secondLst' is null.

Assert.IsInstanceOfType

This method verifies whether the object is of the specified System.Type. The test fails if the type does not match.

Method

Description

Assert.IsInstanceOfType(Object, Type)

This method is used for verifying whether the object is of the specified System.Type.

For example, the following code verifies whether the object is of type ArrayList:

Hashtable obj = new Hashtable(); Assert.IsInstanceOfType(obj, typeof(ArrayList));

The test fails as the obj object is not of type ArrayList. The error message returned would be like:

Assert.IsInstanceOfType failed. Expected type:<System.Collections.ArrayList>. Actual type:<System.Collections.Hashtable>.

Assert.IsInstanceOfType(Object, Type, String)

This is the overloaded method for the preceding method with an additional parameter; the third parameter is the message to be displayed in case the test fails.

Assert.IsInstanceOfType(Object, Type, String, Object[])

The purpose of this method is same as that of the preceding methods; but the additional parameter is the formatter to be applied on the error message displayed if the test fails.

StringAsserts

This is another Assert class within the Unit test namespace Microsoft.VisualStudio.TestTools.UnitTesting that contains methods for common text-based assertions. StringAssert contains the following methods with additional overloaded methods. Overloaded methods are the methods with the same name but with additional or optional parameters to change the behavior of the method based on the parameter values supplied to the method.

StringAssert.Contains

This method verifies if the second parameter string is present in the first parameter string. The test fails if the string is not present. There are three overloaded methods for StringAssert.Contains. The third parameter specifies the message to be displayed if the assertion fails, and the fourth parameter specifies the message formatter to be applied on the error message for the assertion failure. The formatters are the placeholders for the parameters values:

  • StringAssert.Contains(String, String)
  • StringAssert.Contains(String, String, String)
  • StringAssert.Contains(String, String, String, Object[])

For example, the following code verifies if the Test string is present in the first string. If not, the message is displayed with the specified format applied to it.

string find = "Testing";
StringAssert.Contains("This is the Test for StringAsserts", find, "The string '{0}' is not found in the first parameter value", find);

The assertion fails with the specified error message added to its default message as StringAssert.Contains failed. String 'This is the Test for StringAsserts' does not contain string 'Testing'. The string 'Testing' is not found in the first parameter value.

StringAssert.Matches

As the name suggests, this method verifies if the first string matches the regular expression specified in the second parameter. These assert methods contain three overloaded methods to display the custom error message and apply formats to the message if the assertion fails:

  • StringAssert.Matches(String, Regex)
  • StringAssert.Matches(String, Regex, String)
  • StringAssert.Matches(String, Regex, String, Object[])

For example, the following code verifies if the string contains any numbers between 0 and 9. If not, the assertion fails with the message specified with the formats.

   Regex regEx = new Regex("[0-9]");
   StringAssert.Matches("This is first test for StringAssert", regEx, "There are no numbers between {0} and {1} in the string", 0, 9);

The error message would be StringAssert.Matches failed. String ''This is first test for StringAssert'' does not match pattern '[0-9]'. There are no numbers between 0 and 9 in the string.

StringAssert.DoesNotMatch

This is the exact opposite of the StringAssert.Matches method. This assert method verifies whether the first parameter string matches the regular expression specified as the second parameter. The assertion fails if it matches. This assert type has three overloaded methods to display the error message and apply the message formatting to it, which is the place holder for the parameter values in the message:

  • StringAssert.DoesNotMatch(String, Regex,)
  • StringAssert.DoesNotMatch(String, Regex, String)
  • StringAssert.DoesNotMatch(String, Regex, String, Object[])

For example, the following code verifies if the first parameter string does not match with the regular expression specified in the second parameter. The assertion fails if it does match and displays the specified error message with the formatting applied to it.

 Regex regEx = new Regex("[0-9]");
 StringAssert.DoesNotMatch("This is 1st test for StringAssert", regEx, "There is a number in the string");

The assertion fails with the error message StringAssert.DoesNotMatch failed. String ''This is 1st test for StringAssert'' matches pattern ''[0-9]''. There is a number in the string.

StringAssert.StartsWith

This is to verify whether a string in the first parameter starts with the value in the second parameter. The assertion fails if the string does not start with the second string. There are three overloaded methods to specify the error message to be displayed and to specify the formatting to be applied to the error message:

  • StringAssert.StartsWith(String, String)
  • StringAssert.StartsWith(String, String, String)
  • StringAssert.StartsWith(String, String, String, Object[])

For example, the following code verifies if the first string starts with the specified second parameter value. The assertion fails if it does not, and displays the specified error message with the specified formatting.

 string startWith = "First";
 StringAssert.StartsWith("This is 1st test for StringAssert", startWith, "The string does not start with '{0}'", startWith);

The assertion fails with the error message StringAssert.StartsWith failed. String ''This is 1st test for StringAssert'' does not start with string ''First''. The string does not start with ''First''.

StringAssert.EndsWith

This is similar to the StringAssert.StartsWith method, but here, it verifies if the first string ends with the string specified in the second parameter. The assertion fails if it does not end with the specified string, and displays the error message. There are three overloaded methods to specify the custom error message and the formatting:

  • StringAssert.EndsWith(String, String)
  • StringAssert.EndsWith(String, String, String)
  • StringAssert.EndsWith(String, String, String, Object[])

For example, the following code verifies whether the first string ends with the specified string as the second parameter. The assertion would fail and display the message with the specified format.

    string endsWith = "Testing";
    StringAssert.EndsWith("This is 1st test for StringAssert", endsWith, "'{0}' is not the actual ending in the string", endsWith);

The error message displayed would be StringAssert.EndsWith failed. String ''This is 1st test for StringAssert'' does not end with string ''Testing''. ''Testing'' is not the actual ending in the string.

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

CollectionAssert

Visual Studio provides another type of assert through the namespace Microsoft.VisualStudio.TestTools.UnitTesting, which helps to verify the objects that implement the ICollection interface. The collections might be of the system collection type or the custom collection type. These CollectionAssert compares and verifies whether the objects implementing the ICollection interface returns the contents as expected.

Consider the following lists. These lists are used in all the collection assert samples featured in this section:

         List<string> firstLst = new List<string>(3);
         firstLst.Add("FirstName");
         firstLst.Add("LastName");

         List<string> secondLst = new List<string>(3);
         secondLst = firstLst;
         secondLst.Add("MiddleName");

         List<string> thirdLst = new List<string>(3);
         thirdLst.Add("FirstName");
         thirdLst.Add("MiddleName");
         thirdLst.Add("LastName");

         List<string> fourthLst = new List<string>(3);
         fourthLst.Add("FirstName");
         fourthLst.Add("MiddleName");

The firstLst list has its maximum index as three, but has only two elements added to it.

The secondLst list has its maximum index as three and firstLst is assigned to it with an additional item MiddleName added to it.

The thirdLst list has its maximum index as three and contains three items in the list.

The fourthLst list also has three as its maximum index but contains only two items.

CollectionAssert.AllItemsAreNotNull

These asserts verifies if any of the items in the collection is not null. The following assertion would pass as none of the items is null in firstLst.

CollectionAssert.AllItemsAreNotNull(firstLst)

The assertion fails if a third item is added, like this:

firstLst.Add(null)

There are three overloaded methods to display the custom error message and to specify the formatting for the message, if the assertion fails:

  • CollectionAssert.AllItemsAreNotNull(ICollection)
  • CollectionAssert.AllItemsAreNotNull(ICollection, String)
  • CollectionAssert.AllItemsAreNotNull(ICollection, String, Object[])

CollectionAssert.AreEquivalent

The CollectionAssert.AreEquivalent method verifies if both the collections are equivalent. It means that even if the items are in different order within the collections, the items should match.

CollectionAssert.AreEquivalent(thirdLst, secondLst);

In the example, notice that the MiddleName is the last item in the secondLst but it is the second item in the thirdLst. But both collections have the same items, so the assertion would pass. The following are the overloaded methods for Collectionassert.AreEquivalent:

  • CollectionAssert.AreEquivalent (ICollection, ICollection)
  • CollectionAssert.AreEquivalent (ICollection, ICollection, String)
  • CollectionAssert.AreEquivalent (ICollection, ICollection, String, Object[])

CollectionAssert.AreNotEquivalent

The CollectionAssert.AreNotEquivalent statement verifies if both first and second parameter collections do not contain the same items. It means that the assert fails even if one item in the first collection is not present in the second collection. In the example, if we remove or replace one of the items from any of the two collections secondLst or thirdLst, the assertion will pass as the items will not match.

thirdLst.Remove("MiddleName"); 
thirdLst.Add("FullName"); 
CollectionAssert.AreNotEquivalent(thirdLst, secondLst);

The following are the method syntax and the overloaded methods for the CollectionAssert.AreNotEquivalent assert to specify the custom error message and the formatting for the message:

  • CollectionAssert.AreNotEquivalent (ICollection, ICollection)
  • CollectionAssert.AreNotEquivalent (ICollection, ICollection, String)
  • CollectionAssert.AreNotEquivalent (ICollection, ICollection, String, Object[])

CollectionAssert.AllItemsAreInstancesOfType

This statement verifies if all the items in the collection are of the type specified in the second parameter. The following code verifies if all the elements of the collection thirdLst are of the string type. The assertion would pass as the items are string:

CollectionAssert.AllItemsAreInstancesOfType(thirdLst, typeof(string))

The following are the syntax and the overloaded methods for the CollectionAssert.AllItemsAreInstacesOfType assert, with parameters for custom error messages and to specify the formats or the placeholders for the parameter values in the message:

  • CollectionAssert.AllItemsAreInstancesOfType(ICollection, Type)
  • CollectionAssert.AllItemsAreInstancesOfType(ICollection, Type, String)
  • CollectionAssert.AllItemsAreInstancesOfType(ICollection, Type, String, Object[])

CollectionAssert.IsSubsetOf

This statement verifies whether the collection in the first parameter contains some or all the elements of the collection in the second parameter. Note that all the items of the first parameter collection should be part of the collection in the second parameter. As per the example, the following assertion will pass as the items in the fourthLst are the subset of items in the thirdLst:

CollectionAssert.IsSubsetOf(fourthLst, thirdLst)

The following are the syntax and the overloaded methods for the CollectionAssert.IsSubsetOf assert:

  • CollectionAssert.IsSubsetOf(ICollection, ICollection)
  • CollectionAssert.IsSubsetOf(ICollection, ICollection, String)
  • CollectionAssert.IsSubsetOf(ICollection, ICollection, String, Object[])

CollectionAssert.IsNotSubsetOf

This statement verifies whether the collection in the first parameter contains at least one element which is not present in the second parameter collection. As per the example, the following assertion would fail as the items in the fourthLst are the subset of items in the thirdLst. It means that there are no items in fourthLst which is not present in thirdLst.

CollectionAssert.IsNotSubsetOf(fourthLst, thirdLst)

Try adding a new element to the fourthLst which is not present in thirdLst such as:

fourthLst.Add("FullName");

Now try the same CollectionAssert statement. The assertion would pass as the fourthLst is not a subset of thirdLst collection.

The following are the syntax and the overloaded methods for the CollectionAssert.IsNotSubsetOf assert to specify the custom error message and the formats for error message:

  • CollectionAssert.IsNotSubsetOf(ICollection, ICollection)
  • CollectionAssert.IsNotSubsetOf(ICollection, ICollection, String)
  • CollectionAssert.IsNotSubsetOf(ICollection, ICollection, String, Object[])

CollectionAssert.AllItemsAreUnique

Verifies whether the items in the collection are unique. The assertion would pass on firstLst. The assertion fails if we add a third item, LastName, which duplicates an existing item:

firstLst.Add("LastName")

The syntax for this method and its two overloaded methods are given here. The additional parameters are to specify the custom error message and formatting for that error message:

  • CollectionAssert.AllItemsAreUnique(ICollection)
  • CollectionAssert.AllItemsAreUnique(ICollection, String)
  • CollectionAssert.AllItemsAreUnique(ICollection, String, Object[])

CollectionAssert.Contains

This assert verifies if any element of the collection specified as the first parameter contains the element specified as the second parameter. The following assert would pass as the FirstName is an element in the fourthLst collection:

CollectionAssert.Contains(fourthLst, "FirstName")

Custom error messages and formats for the assertion failure can be specified. This assert has two overloaded methods in addition to the default method:

  • CollectionAssert.Contains(ICollection, Object)
  • CollectionAssert.Contains(ICollection, Object, String)
  • CollectionAssert.Contains(ICollection, Object, String, Object[])

CollectionAssert.DoesNotContain

This is the exact opposite of the CollectionAssert.Contains statement. This assert verifies if any of the elements in the first parameter collection does not equal to the value specified as the second parameter:

CollectionAssert.Contains(fourthLst, "Phone Number")

Custom error messages and formatters for the assertion failure can be specified. This assert has two overloaded methods in addition to the default method:

  • CollectionAssert.DoesNotContain(ICollection, Object)
  • CollectionAssert.DoesNotContain(ICollection, Object, String)
  • CollectionAssert.DoesNotContain(ICollection, Object, String, Object[])

CollectionAssert.AreEqual

This method verifies if both collections are equal in size. The following assertion fails as the number of items added to the firstLst is different from the thirdLst:

CollectionAssert.AreEqual(firstLst, thirdLst)

The assertion would pass if we add the same number of items as firstLst to the thirdLst, or assign the firstLst to thirdLst making both the arrays identical:

thirdLst = firstLst;

This assert type has six overloaded methods:

  • CollectionAssert.AreEqual(ICollection, ICollection)
  • CollectionAssert.AreEqual(ICollection, ICollection, IComparer)
  • CollectionAssert.AreEqual(ICollection, ICollection, IComparer, String)
  • CollectionAssert.AreEqual(ICollection, ICollection, IComparer, String, Object[])
  • CollectionAssert.AreEqual(ICollection, ICollection, String)
  • CollectionAssert.AreEqual(ICollection, ICollection, String, Object[])

The parameters String and Object[] and custom formats can be used for custom error messages in case of assertion failure.

IComparer can be used if we have custom objects in the collection and we want to use a particular property of the object for comparison. For example, if a collection contains a list of Employee objects, having the FirstName, LastName, and EmployeeID of each employee, we may want to sort and compare the elements in the collection based on the FirstName of the employees. We may want to compare the two collections containing the employees list based on the FirstName of the employees. To do this, we have to create the custom comparer.

Consider the following Employee class, which has an EmployeeComparer class that compares the FirstName in the Employee implemented from the IComparable interface:

   public class Employee : IComparable
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int ID { get; set; }

        public Employee (string firstName, string lastName, int employeeID)
        {
            FirstName = firstName;
            LastName = lastName;
            ID = employeeID;
        }

        public int CompareTo(Object obj)
        {
             Employee emp = (Employee)obj;
             return FirstName.CompareTo(emp.FirstName);
        }

        public class EmployeeComparer : IComparer
        {
            public int Compare(Object one, Object two)
            {
                Employee emp1 = (Employee)one;
                Employee emp2 = (Employee)two;
                return emp1.CompareTo(two);
            }
    }

Now create two collections of type List and add employees to the lists as shown below. The first names of the employees are the same in both lists, but the last names and the IDs vary, as shown in the following code:

            List<Employee> EmployeesListOne = new List<Employee>();
            EmployeesListOne.Add(new TestLibrary.Employee("Richard", "King", 1801));
            EmployeesListOne.Add(new TestLibrary.Employee("James", "Miller", 1408));
            EmployeesListOne.Add(new TestLibrary.Employee("Jim", "Tucker", 3234));
            EmployeesListOne.Add(new TestLibrary.Employee("Murphy", 
                                 "Young", 3954));
            EmployeesListOne.Add(new TestLibrary.Employee("Shelly", "Watts", 7845));

            List<Employee> EmployeesListTwo = new List<Employee>();
            EmployeesListTwo.Add(new TestLibrary.Employee("Richard", "Smith", 4763));
            EmployeesListTwo.Add(new TestLibrary.Employee("James", "Wright", 8732));
            EmployeesListTwo.Add(new TestLibrary.Employee("Jim", "White", 1829));
            EmployeesListTwo.Add(new TestLibrary.Employee("Murphy", "Adams", 2984));
            EmployeesListTwo.Add(new TestLibrary.Employee("Shelly", "Johnson", 1605));

Now in the test method, use CollectionAssert.AreEqual to compare the preceding collections.

CollectionAssert.AreEqual(EmployeesListOne, EmployeesListTwo, "The collections '{0}' and '{1}' are not equal", "EmployeesListOne", "EmployeesListTwo");

This assertion would fail because the objects in the collection are not the same. Even if you update the employee object properties to be the same in both the collections, it will fail because the objects are not the same. The error message would be the specified custom message with the specified formatters.

But we can use the custom comparer we created to compare the collection objects based on the FirstName element which is used in the comparer. We can create the custom comparer on any of the object properties:

        TestLibrary.Employee.EmployeeComparer comparer = new TestLibrary.Employee.EmployeeComparer();
        CollectionAssert.AreEqual(EmployeesListOne, EmployeesListTwo, comparer, "The collections '{0}' and '{1}' are not equal", "EmployeesListOne", "EmployeesListTwo");

The assertion would pass now as the comparison is done on the first name of the elements in both the collection.

ollectionAssert.AreNotEqual

This is similar to the CollectionAssert.AreEqual but this will verify if the collections are not equal. This assert type also has multiple overloaded methods similar to the CollectionAssert.AreEqual:

  • CollectionAssert.AreNotEqual(ICollection, ICollection)
  • CollectionAssert.AreNotEqual(ICollection, ICollection, IComparer)
  • CollectionAssert.AreNotEqual(ICollection, ICollection, IComparer, String)
  • CollectionAssert.AreNotEqual(ICollection, ICollection, IComparer, String, Object[])
  • CollectionAssert.AreNotEqual(ICollection, ICollection, String)
  • CollectionAssert.AreNotEqual(ICollection, ICollection, String, Object[])

AssertFailedException

This is to catch the exception thrown when the test fails. This exception is thrown whenever there is a failure in the assert statement.

The code in the following screenshot verifies if the fourthLst contains the string, Phone Number. The assertion fails and the exception, AssertFailedException is caught using the catch block. For this example, we will add the exception message and a custom message to the test trace.

AssertFailedException

The preceding code clearly shows that the code has thrown the exception, AssertFailedException, and is caught by the exception code block. Now the test will pass because of the expected exception thrown by the test. The Test Result details will show the details of the result. The following screenshot depicts the Test Result:

AssertFailedException

UnitTestAssertionException

This is the base class for all unit test exceptions. If we have to write our own custom Assertion class, we can inherit from UnitTestAssertionException to identify the exceptions thrown from the test.

The code debug image with the exception shown in the previous section shows the AssertFailedException which is derived from UnitTestAssertException.

ExpectedExceptionAttribute

This attribute can be used to test if any particular exception is expected from the code. The attribute expects the exact exception that is expected to arise out of the code to be specified as the parameter. Let's discuss this step-by-step with the help of an example. The following code shows the custom exception which is derived from the application exception. This custom exception does nothing, but just sets a message:

namespace TestLibrary
{
    class MyCustomException : ApplicationException
    {
        public string CustomMessage { get; set; }

        public MyCustomException(string message)
        {
            CustomMessage = message;
        }
    }
}

The class contains a method which returns the total price, but throws the custom exception with a message if the total price is less than zero.

        public double GetTotalItemPrice(int count) {
            double price = 10.99; 
            double total;
                total = count * price;
                if (total < 0) {
                    throw new TestLibrary.MyCustomException("the total is less than zero");
                }
                return total;
        }

Create a unit test method for the preceding method that returns the total item price:

        [TestMethod()]
        public void GetTotalItemPriceTest()
        {
            Class1 target = new Class1(); 
            int count = 0; 
            double expected = 0F; 
            double actual;
            actual = target.GetTotalItemPrice(count);
            Assert.AreEqual(expected, actual);
        }

To test the preceding method, set the count to a value less than zero and run the test from the Test Explorer window. The assertion will fail. For example, for a value of -1 the assertion will fail with the following message, which says the application thrown by an exception is of type MyCustomException:

ExpectedExceptionAttribute

The error message was thrown by the original method, not the test method. But the intention here is to test if the original method throws the expected exception. To achieve that, add the ExpectedException attribute to the test method as follows and run the test by setting different values for the variable count:

        [TestMethod()]
        [ExpectedException(typeof(TestLibrary.MyCustomException))]
        public void GetTotalItemPriceTest()
        {
            Class1 target = new Class1(); 
            int count = -1; 
            double expected = 0F; 
            double actual;
            actual = target.GetTotalItemPrice(count);
            Assert.AreEqual(expected, actual);
        }

The preceding test would pass as the method throws MyCustomException, which means that the method resulted in an exception because of its total value, which is less than zero.

Any exception can be included as an attribute to the Test method to verify if the actual method throws the exception. This is very useful in case of very complex methods, where there is a high possibility of getting exceptions such as divide by zero, File IO, or file/folder access permissions.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.37.191