Use Assert classes for unit testing

Use the Assert classes of the Microsoft.VisualStudio.TestTools.UnitTesting namespace to verify specific functionality. A unit test method exercises the code of a method in your application's code, but it reports the correctness of the code's behavior only if you include Assert statements.

Kinds of asserts

The Microsoft.VisualStudio.TestTools.UnitTesting namespace provides several kinds of Assert classes.

In your test method, you can call any methods of the Microsoft.VisualStudio.TestTools.UnitTesting.Assert class, such as Assert.AreEqual. The Assert class has many methods to choose from, and many of the methods have several overloads.

Compare strings and collections

Use the CollectionAssert class to compare collections of objects, or to verify the state of a collection.

Use the StringAssert class to compare and examine strings. This class contains a variety of useful methods, such as StringAssert.Contains, StringAssert.Matches, and StringAssert.StartsWith.

Exceptions

The AssertFailedException exception is thrown whenever a test fails. A test fails if it times out, throws an unexpected exception, or contains an assert statement that produces a Failed result.

The AssertInconclusiveException is thrown whenever a test produces a result of Inconclusive. Typically, you add an Assert.Inconclusive statement to a test that you are still working on, to indicate it's not yet ready to be run.

Note

An alternative strategy is to mark a test that is not ready to run with the IgnoreAttribute attribute. However, this has the disadvantage that you can't easily generate a report on the number of tests that aren't implemented.

If you write a new assert exception class, inherit from the base class UnitTestAssertException to make it easier to identify the exception as an assertion failure instead of an unexpected exception thrown from your test or production code.

To verify that an exception you expect to be thrown by a method in your application code is actually thrown, use the Assert.ThrowsException method.

See also