Introduction to Assertions

Learn about assertions and why they are crucial for automated testing.

An assertion is a fundamental part of any automated test setup. We use it to verify that the outcome of the functionality we test meets our expectations. For example, if we test a method that performs calculations and returns a numeric value, we can use an assertion to verify that the expected value is returned for the specified set of parameters.

There are several different types of assertions, such as xUnit, used by automated testing frameworks. We can use assertions to verify if the output value matches the expected value or if the size of the collection is modified as expected. Moreover, we can use assertions to determine if a specific exception type is thrown under specific conditions.

When an assertion is executed, here is what happens:

  • If the condition being tested matches the expected condition of the assertion, the assertion is considered correct, and the code moves to the next statement.

    • If all assertions pass and the code exits the test method, the test is marked as passed.

    • The same happens if there are no assertions in the method. However, this represents a poorly written test.

  • If the condition outlined in the assertion doesn’t match the actual output, an exception is thrown, and the test is marked as a failure.

    • No further lines of code are executed, and the method exits immediately.

    • In xUnit, this is represented by the AssertionException type.

Using xUnit assertions

xUnit has a built-in static Assert class inside the Xunit namespace. This class contains multiple methods that can perform different types of assertions. The following playground demonstrates how some of them work:

Get hands-on with 1200+ tech skills courses.