I'm trying to build my first unit tests and have a class that increments and decrements an instance counter in it's constructor and destructor respectively. I have a test to make sure this works but it fails, it seems that other instances of the class from my other tests aren't having their destructor called when they go out of scope.
public class Customer
{
public Customer()
{
++InstanceCount;
}
public Customer(int customerId)
{
CustomerId = customerId;
++InstanceCount;
}
~Customer()
{
--InstanceCount;
}
public static int InstanceCount { get; private set; }
}
[TestClass]
public class CustomerTest
{
[TestMethod]
public void FullNameLastNameEmpty()
{
//--Arrange
Customer customer = new Customer {FirstName = "John"};
const string expected = "John";
//--Act
string actual = customer.FullName;
//--Assert
Assert.AreEqual(expected, actual);
}
[TestMethod]
public void StaticTest()
{
//--Arrange
Customer[] customers =
{
new Customer {FirstName = "John"},
new Customer {FirstName = "Jane"},
new Customer {FirstName = "Jeff"}
};
//--Act
//--Assert
Assert.AreEqual(3, Customer.InstanceCount);
}
}
I'm not passing a reference anywhere so customer should be deallocated but it is not, I've even tried calling GC.Collect() at the start of StaticTest() to force calls to the destructor but still no luck.
Could someone explain why this is happening and how to fix it.