In previous post (http://csharpmatters.blogspot.com/2009/03/unit-testing-in-visual-studio-2008-team.html) I’ve described new test functionality in VS2008 TS.
In this post I drill down unit tests inside VS2008 more detail.
VS built-in units tests use attributes (similar to NUnit).
Attributes are used to denote various test methods and test classes.
Common attributes:
[TestClass()] mark class representing a unit test case. Class need to be public.
[TestMethod()]marks Test Method
Another popular attributes:
[ClassInitialize()] –code need to be run before running the first test in the class
[ClassCleanup()] – code need to be run after all tests in class
[TestInitialize()] – code need to be run before each test
[TestCleanup ()] – code need to be run after each test
Example:
[TestClass()]
public class MyClassTest
[TestMethod()]
public void MyClassInitTest()
VS provides Assert class with static methods to check various conditions.
All Asserts methods accept 2 parameters: Boolean condition and exception message provided by user. If condition is FALSE: test exception with custom msg is thrown.
More about assert methods here: http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.assert_members.aspx
If you worked with nUnit tool you can see a lot of similarities.
(Please note UI testing is not supported in the current version of unit testing with VS.NET 2008)
Let’s follow nUnit example (http://www.nunit.org/index.php?p=quickStart&r=2.4.7) but using VS built-in tests this time.
Production code example:
Test Class code:
After test run you will see that test failed with message:
TransferFundsTest UnitTests Assert.AreEqual failed. Expected:<250>. Actual:<150>.
All because production method TransferFunds() has no implementation yet.
Let’s correct that as follows:
public void TransferFunds ( Account destination, float amount ) {
destination.Deposit( amount );
Withdraw(amount);
}
After that correction test is passed.
Please find more about testing in next part(s) of post
Labels: Testing