Assert statements

The assert statement is used for comparing the result from the method with the expected result and then passing or failing the test based on the match. Whatever may be the result produced by the method, the end result of the test method depends on the return value of the assert method. The assert statement establishes the result. There are different statements supported by the Assert class to set the return value to Pass, Fail, or Inconclusive. If the assert statement is not present in the test method, the test method will always return a Pass. 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. Assert.AreEqual has two parameters, one as expected which is the expected value that should be returned by the CalculateTotalPrice method. The 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. Returns Fail if there is a mismatch between these two values:

[TestMethod()]
public void CalculateTotalPriceTest()
{
Class1 target = 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 = target.CalculateTotalPrice(quantity);
Assert.AreEqual(expected, actual);
Assert.Inconclusive("Verify the correctness of this test method.");
}

The test method also has the Assert.Inconclusive statement to return the result as Inconclusive if the test method is not complete. We can remove this line if the code is complete and we do not want the test result to be Inconclusive. In the previous code, if we run the test without setting the value for quantity and expected, the return would be Inconclusive. Now set the value for quantity and expected as:

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

The result returned would be a Fail 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. We have seen only one type of assert statement. There are many other asserts which we can use in test methods for passing or failing the test.

Types of asserts

The Assert classes in VSTS contain the comparison and conditional testing capabilities. The namespace Microsoft.VisualStudio.TestTools.UnitTesting in VSTS contains all these asserts. The actual and the expected values are compared based on the type of assert used and the result decides the test pass or failure.

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 the additional or optional parameters to the method in case we want custom messages or additional functionality to be added. For example, the assert method provides an overloaded method to compare the values within a specified accuracy, which we will see in detail when comparing double values.

Let us consider a simple Item class 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;
}

Generate the unit test for the preceding method and set the properties for the local expected object similar to the one shown here:

[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 preceding 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 Assert.AreEqual() and the result for the preceding code samples:

Method

Description

Assert.AreEqual(Object, Object);

Verifies if both the objects are equal

The test fails because the actual and the expected 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 will pass as both the objects are the same now.

Assert.AreEqual(Object, Object, String)

Used for verifying two objects and displaying 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 displaying 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 casing 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)

If the property value for expected is.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 casing to include for comparison; 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 as 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 test would produce the result if the test fails as 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 but the only difference is 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 or not 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 type of overloaded assert methods for the assert type AreSame to check if the objects are the 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:

ArrayList A = new ArrayList(5);

ArrayList B = A;

Assert.AreSame(A, B);

Both the 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 the object variables refer to the same object; if not, the message will be displayed; for example, the following code compares the two objects A and B:

ArrayList A = new ArrayList(5);

ArrayList B = new ArrayList(10);

Assert.AreSame(A, B, "The objects are not same");

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

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

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

ArrayList A = new ArrayList(5);

ArrayList B = new ArrayList(10);

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

The test fails with the output Assert.AreSame failed. The objects A and B are not same.

Assert.AreNotSame

This Assert is used for verifying whether the 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 A and B are not the same. If they are the same, the test fails with the specified error message with the specified formatting applied to it:

ArrayList A = new ArrayList(5);
ArrayList B = A;
Assert.AreNotSame(A, B, "The test fails because the objects {0} and {1} are same", "A", "B");

The preceding test fails with the message, Assert.AreNotSame failed. The test fails because the objects A and B 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 if the method is incomplete and we cannot determine whether the output is true or false. We can set the assertion to be inconclusive until we complete the method 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 with the condition false.

Assert.IsTrue(String, Object[])

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

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

ArrayList A = new ArrayList(5);

ArrayList B = new ArrayList(10);

Assert.IsTrue(A == B, "Both '{0}' and '{1}' are not equal", "A", "B");

The output message for the above test would be Assert.IsTrue failed. Both 'A' and 'B' 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; the 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[])

Verify the condition and display the message if the test fails with the condition true and apply the specified formatting to the message.

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

ArrayList A = new ArrayList(5); ArrayList B = A; Assert.IsFalse(A == B, "Both '{0}' and '{1}' are equal", "A", "B");

The output message for the preceding test would be Assert.IsFalse failed. Both 'A' and 'B' are equal.

Assert.IsNull

This is useful in verifying whether the 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 and display 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:

ArrayList A = new ArrayList(5);

ArrayList B = A;

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

The preceding code fails the test and displays the error message Assert.IsNull failed. Object 'B' 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:

ArrayList B = null;

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

The preceding code fails the test and displays the error message, Assert.IsNotNull failed. Object 'B' 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 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 object obj is not of type ArrayList. The error message returned would be 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 the 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 the common text-based assertions. StringAssert contains the following methods with additional overloaded methods. Overloaded methods are the additional or optional parameters to the method in case we want custom messages.

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 to 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 string, Test, is present in the first string. If not, the message is displayed with the 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 as 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 formatters.

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 StringAssert.Matches. 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, but here, it verifies if the first string ends with the specified string 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 will fail and display the message with the specified formatting.

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.

CollectionAssert

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

We will consider the following array lists and find out the usage of Collection Assert Statements. These array lists are used in all the collection assert samples given here in this section:

ArrayList firstArray = new ArrayList(3);
firstArray.Add("FirstName");
firstArray.Add("LastName");
ArrayList secondArray = new ArrayList(3);
secondArray = firstArray;
secondArray.Add("MiddleName");
ArrayList thirdArray = new ArrayList(3);
thirdArray.Add("FirstName");
thirdArray.Add("MiddleName");
thirdArray.Add("LastName");
ArrayList fourthArray = new ArrayList(3);
fourthArray.Add("FirstName");
fourthArray.Add("MiddleName");

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

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

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

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

CollectionAssert.AllItemsAreNotNull

This assert verifies if any of the items in the collection is not null. The assertion will pass as none of the items is null in firstArray.

CollectionAssert.AllItemsAreNotNull(firstArray)

The assertion will fail if we add the third item as:

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

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

CollectionAssert.AreEquivalent(thirdArray, secondArray);

In the example, we can see that MiddleName is the last item in the secondArray but it is the second item in the thirdArray. But both the collections have the same items, so the assertion will 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 assert CollectionAssert.AreNotEquivalent statement verifies if both the 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 present in the second collection. In the example, if we remove or replace one of the items from any of the two collections secondArray or the thirdArray, the assertion will pass as the items will not match.

thirdArray.Remove("MiddleName");
thirdArray.Add("FullName");
CollectionAssert.AreNotEquivalent(thirdArray, secondArray);

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 specified/expected type in the second parameter. The following code verifies if all the elements of the collection thirdArray is of type, string. The assertion will pass as the items are string:

CollectionAssert.AllItemsAreInstancesOfType(thirdArray, 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 of the elements of the collection in the second parameter. But 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 fourthArray are the subset of the items in the thirdArray:

CollectionAssert.IsSubsetOf(fourthArray, thirdArray)

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 will fail as the items in the fourthArray are the subset of the items in the thirdArray. It means that there are no items in fourthArray which are not present in thirdArray.

CollectionAssert.IsNotSubsetOf(fourthArray, thirdArray)

Try adding a new element to the fourthArray which is not present in thirdArray such as:

fourthArray.Add("FullName");

Now try the same CollectionAssert statement. The assertion will fail as the fourthArray is not a subset of the thirdArray collection.

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

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

CollectionAssert.AllItemsAreUnique

This verifies whether the items in the collection are unique. The following assertion will pass as per the same collection. The assertion fails if we add a third item, LastName, which duplicates the existing item:

firstArray.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 the formats for the error message.

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

CollectionAssert.Contains

This assert verifies if any of the elements of the collection specified as the first parameter contain the element specified as the second parameter. The following assert will pass as the FirstName is an element in the fourthArray collection:

CollectionAssert.Contains(fourthArray, "FirstName")

We can specify the custom error message and custom formats for the assertion failure. 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 is not equal to the value specified as the second parameter:

CollectionAssert.Contains(fourthArray, "Phone Number")

We can specify the custom error message and custom formatters for the assertion failure. 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 the collections are equal. The following assertion fails as the number of items added to the firstArray is different from the thirdArray.

CollectionAssert.AreEqual(firstArray, thirdArray)

The assertion will pass if we add the same items from firstArray to the thirdArray or assign the firstArray to thirdArray which makes both the arrays equal:

thirdArray = firstArray;

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 parameter String and Object[] can be used when we need a custom error message and formatters for the error message in case of assertion failure.

IComparer can be used if we have the custom objects in the collection and if 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 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 a 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 the type ArrayList and add employees to the lists. The first names of the employees are the same in both the lists but the last names and the IDs vary.

ArrayList EmployeesListOne = new ArrayList();
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));
ArrayList EmployeesListTwo = new ArrayList();
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 will 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 will 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 will pass now as the comparison is done on the first name of the elements in both the collection.

CollectionAssert.AreNotEqual

This is similar to 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 of the assert statement.

The following code verifies if the fourthArray 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 shows that the code has thrown the exception, AssertFailedException, and is caught by the exception code block. Now the test will pass as the expected exception is thrown by the test. The test result details will show the details of tracing. The following screenshot depicts the test result with the trace:

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 the class from the UnitTestAssertionException class to identify the exceptions thrown from the test.

The code debug image with the exception shown in the previous section shows 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 by choosing the Create Unit Test option from the context menu. The following code shows the unit test method for the preceding code 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 view 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

This is not what we want here. This is the application we are going to use for testing the expected exception.

Now we have to test the method GetTotalItemPrice for MyCustomException. To do this, add the ExpectedException attribute to the test method as shown here 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 will 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.

We can include any exception as an attribute to the test method and verify the actual method if it actually throws an exception. This is very useful in the 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.141.47.163