Effective Test Driven Development & Unit Testing with Visual Studio 2010 Abhimanyu Singhal Lead Consultant iMentor Knowledge Services
About Me History First Laid Hands on Computers in 1994 – Been a Geek for Quite Some time Worked on different platforms and technologies Career Focus – Embedded Systems and Native Development Currently Help companies use Visual Studio Team System as an ALM Platform High-End Technical Consultancy and Training
Why is TDD Good Thinking about tests pushes developer to understand better the gathered requirements Reduces the over engineered code (dead code) Unit Tests help to check that any new modification wont break the existing features. TDD increases software flexibility TDD code is more decoupled
Visual Studio Team Test A Visual Studio integrated unit-testing framework Code generation of test method stubs. Running tests within the IDE. Incorporation of test data loaded from a database. Code coverage analysis once the tests have run.
TestMethodAttribute Class Designates a Method as a Test Method Found in Microsoft.VisualStudio.QualityTools.UnitTesting.Framework Namespace TestMethod has to be an instance method with no paramters Method name is irrelevant because reflection searches for TestMethod Attribute
TestClassAttribute Class Class containing the test method is designated TestClass Attribute
Found in Microsoft.VisualStudio.QualityTools.UnitTesting.Framework Namespace
Team Test Uses Reflection to find Class with TestClass Attribute and Method with TestMethod Attribute and runs it
Running and Executing Tests From Visual Studio As Part of Build Process From Command Line
ExpectedException Attribute Takes a Parameter which is Exception Type to watch for If Exception does not occur test fails The Second parameter (string) is optional is the error message displayed when exception is not thrown
Loading Test Data From Database Use Test Properties Window Add TestData Attribute Source Type Connection String TableName DataAccessMethod
The TestContext Provides associated data through DataRow Property TestDirectory, TestName Mesuring Test Time using BeingTimer() EndTimer()
Code Coverage Determines how much code is tested Shows Percentage of Code Executed Highlights code to show which lines are executed
Initializing and Cleaning Up Tests TestInitialize Attribute TestCleanup Attribute Code to be run before and after each test method Other Attributes for Lifetime Methods AssemblyInitializeAttribute/AssemblyCleanupAttribute ClassInitializeAttribute/ClassCleanupAttribute.
Guidance – Unit Testing Keep Testing Code in Separate Assemblies Check for cleanup during test setup and execute the cleanup prior to the setup as necessary Avoid creating dependencies between tests, each test should be autonomous. Create one test class corresponding to each class within the production code. Avoid creating other machine dependent tests Create mock objects to test interfaces