20.5. Running Tests Part 2:

Now that you have walked through a few [TestMethod] examples, we are going to cover a few testing methods you might find useful.

20.5.1. [TestInitialize]

While [TestClass] and [TestMethod] are required to run tests, there are many other attributes you may find useful as your test files grow in scope. One such item to know is [TestInitialize]. Methods with the attribute [TestInitialize] will run before each test method is run in a class.

In the case of CarTest, it would be nice to not need to create a new Car instance for each test we write. In your TestInitialGasTank() method, remove the line initiating test_car. Above your relevant test, add the following [TestInitialize] method:

Car test_car;

public void CreateCarObject()
   test_car = new Car("Toyota", "Prius", 10, 50);

Now, run the test project and ensure your test still passes.

20.5.2. [TestCleanup]

[TestCleanup], conversely, defines a set of conditions to be met after each test in a suite is run.


We won’t encounter a scenario where we ask you to use [TestCleanup] in this class. As you explore writing your own unit tests, you may find yourself in a situation where you need or want it. One use case for [TestCleanup] might be testing database transactions. You don’t want changes to a database to persist after test execution, so you can use [TestCleanup] to rollback, or reverse, a test transaction.

You can find more information on this attribute and other items available in the Visual Studio testing namespace here.

20.5.3. Common Assert Methods

In addition to the very commonly used Assert.AreEqual() method you see above, here are a few other methods you should have in your unit testing playbook.

MSTest Assert Methods
Assertion Description
AreEqual(expected, actual, optional_delta) Asserts that two values, expected and actual, are equal to each other (optionally, within a given range of difference)
IsFalse(condition) Asserts that a given condition is false
IsTrue(condition) Asserts that a given condition is true
IsNotNull(object) Asserts that a given object is not null

Checkout the Assert class for a full listing of methods.

20.5.4. Check Your Understanding


Write another version of TestInitialGasTank() using IsFalse(), comparing the value to 0.

  1. Assert.IsFalse(Car.GasTankLevel == 0);
  2. Assert.IsFalse(test_car.GasTankLevel == 0);
  3. Assert.False(test_car.GasTankLevel == 0);
  4. Assert.IsFalse(test_car.GasTankLevel = 0);


Write another version of TestInitialGasTank() using IsTrue().

  1. Assert.IsTrue(test_car.gasTankLevel == 10);
  2. Assert.IsTrue(Car.GasTankLevel == 10);
  3. Assert.IsTrue(test_car.GasTankLevel == 0);
  4. Assert.IsTrue(test_car.GasTankLevel == 10);