Unit Testing - VSTS

Download Unit Testing - VSTS

Post on 13-Nov-2014




1 download

Embed Size (px)


It gives an idea about how unit testing can be done using VSTS


<p>What is VSTS? Visual Studio 2005 Team System is a productive, integrated, and extensible suite of lifecycle tools that enable greater communication and collaboration among software development teams. One of the features of VSTS includes: Setup Unit tests (replacing NUNit). Create and run manual tests, Web tests, and load tests. The product is called Visual Studio Team Test A client tool for those devoted to testing that enables them to design, manage, and execute manual, unit and load tests. It is designed to aid in the process of software development. VSTT enables 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.</p> <p>Team Test VSTS takes testing a step further than simple unit testing by making them available in the Team Test product geared specifically for testers. This product enables testers to execute the unit tests developers create in a systematic fashion to ensure that code checked in by multiple developers passes previously constructed tests. This is an example of another testing best practice referred to as regression testing. Team Test goes even further by making testers first-class citizens of the project by highlighting the importance of testing at the team level through a test authoring and execution environment. That environment includes additional test types such as Web Tests, Load Tests (similar to the tool Application Center Test tool that ships with Visual Studio .NET 2003), Manual Tests, and Ordered Tests and test case management all integrated into Team Foundation.</p> <p>Advantages/Benefit of Unit Tests The unit tests serve as the first users of your system and will frequently identify design issues or functionality that is lacking. A well-written test suite provides the original developer with the freedom to pass the system off to other developers for maintenance and further enhancement.</p> <p>Cheaper cost - It is a component that comes along with the MS Visual Studio IDE. Disciplined Development - Well defined deliverable for the developer and more quantifiable progress. Often, just considering a test case will identify issues with an approach/design. Facilitates change and Reduces code fragility Unit testing allows the programmer to refractor code at a later date, and make sure the module still works correctly (i.e. regression testing). Simplifies integration - Unit testing helps eliminate uncertainty in the pieces themselves and can be used in a bottom-up testing style approach. By testing the parts of a program first and then testing the sum of its parts, integration testing becomes much easier. Documentation - Unit testing provides a sort of "living document". Clients and other developers looking to learn how to use the class can look at the unit tests to determine how to use the class to fit their needs and gain a basic understanding of the API. Relative cost to fix defects graph - The earlier an error is caught the cheaper it is to fix.</p> <p>It takes the typical developer time and practice to become comfortable with unit testing. Once a developer has been saved enough time by unit tests, he or she will latch on to them as an indispensable part of the development process. Unit testing does require more explicit coding, but this cost will be recovered, and typically exceeded, when you spend much less time debugging your application. Writing effective unit tests Always separate your unit test assemblies from the code you are testing. Avoid altering the code you are testing solely to allow easier unit testing. Each test should verify a small slice of functionality. Do not write long sequential unit tests that verify a large number of items. All tests should be autonomous. Avoid creating tests that rely on other tests to be run beforehand.</p> <p>Test both expected behavior (normal workflows) and error conditions (exceptions and invalid operations).</p> <p>Test-driven development Test-driven development (TDD) is the practice of writing unit tests before writing the code that will be tested. TDD encourages following a continuous cycle of development involving small and manageable steps.</p> <p>The most common way to determine success in unit tests is to compare an expected result against an actual result. The Assert class features many methods that enable you to make these comparisons quickly. Team System Unit Test Assertions Assert.AreEqual, Assert.AreNotEqual Assert.AreNotSame, Assert.AreSame Assert.Equals Assert.Fail Assert.Inconclusive Assert.IsFalse Assert.IsInstanceOfType</p> <p>Assert.IsNotInstanceOfType Assert.IsNotNull Assert.IsNull Assert.IsTrue The Microsoft.VisualStudio.TestTools.UnitTesting namespace includes a class, Collection Assert, containing useful methods for testing the contents and behavior of collection types.</p> <p>Similar to CollectionAssert, the StringAssert class contains methods that enable you to easily make assertions based on common text operations. The following table describes the methods supported by StringAssert.</p> <p>The unit test framework offers attributes to identify such methods. They are grouped into three levels: Test, Class, and Assembly. The levels determine the scope and timing of execution for the methods they decorate. The following table describes these attributes.</p> <p>Some other Attributes are TestClass TestMethod Description Ignore ExpectedException</p> <p>The generated test project contains four files related to testing.</p> <p>File Name AuthoringTest.txt</p> <p>Purpose Provides notes about authoring tests including instructions on adding additional tests to the project. Includes generated test for testing the LogonInfo() constructor along with methods for test initialization and cleanup. Provides a template to fill in with instructions for manual testing. An empty unit test class skeleton in which to place additional unit tests.</p> <p>LogonInfoTest.cs</p> <p>ManualTest1.mht UnitTest1.cs</p> <p>Steps to Create a Unit Test Case</p> <p>1. Right click on a method in the solution. 2. By default, the Output project setting is for a new Visual Basic project, but C#and C++ test projects are also available. We will select Visual C# and click the OK button, followed by entering a project name.</p> <p>3. Implement the code in the test method.4. Run the Test</p> <p>To enable this action, we need to right-click on the project within the solution explorer and click Set as Startup Project. Next, use the Debug-&gt;Start (F5) or Debug-&gt;Start without Debugging (Ctrl+F5) menu items to begin running the tests.</p> <p>5. Test Results window will be shown after executing all tests.Example: 1. Open Visual Studio IDE Click Start &gt; Programs &gt; Microsoft Visual Studio 2005 &gt;Microsoft Visual Studio 2005 2. Creating a Sample C# Project File--&gt;New Project--&gt;Chose from Templates as below</p> <p>3. Add a simple "add" method to the code. This method accepts 2 arguments, adds them and returns the total.</p> <p>4. Create Unit Test for "add" method by right clicking on the method</p> <p>5. This will display a dialog box for generating unit tests into a different project (see Figure below). By default, the Output project setting is for a new Visual Basic project, but C# and C++ test projects are also available. For this article, we will select as C# project click the OK button.</p> <p>6. Now enter a Test project name of computeTest for the project name.</p> <p>7. The generated test project contains following files related to testing. File Name Purpose</p> <p>AuthoringTest.txt Provides notes about authoring tests including instructions on adding additional tests to the project. computeTest.cs Includes generated test for testing the add(x,y) method along with methods for test initialization and cleanup.</p> <p>8. In addition to some default files; the generated test project contains references to both the Microsoft.VisualStudio.QualityTools.UnitTestFramework and the computation</p> <p>project, which the unit tests are executing against. The former is the testing framework assembly the test engine depends on when executing the unit tests. The latter is a project reference to the target assembly we are testing.</p> <p>There are two important attributes related to testing with Team Test. First, the designation of a method as a test is through the TestMethodAttribute attribute. In addition, the class containing the test method has a TestClassAttribute attribute. Both of these attributes are found in the: Microsoft.VisualStudio.QualityTools.UnitTesting.Framework namespace. Team Test uses reflection to search a test assembly and find all the TestClass decorated classes, and then find the corresponding TestMethodAttribute decorated methods to determine what to execute. One other important criterion, validated by the execution engine but not the compiler, is that the test method signature be an instance method that takes no parameters. The test method AddTest() instantiates the target computaion class before checking for assertion. When the test is run, the Assert.Inconclusive() provides an indication that it is likely to be missing the correct implementation.</p> <p>9. Providing input values to test method Updated addTest() Implementation after editing to provide input values Note that the checks are done using the Assert.AreEqual() method.</p> <p>10. Running Tests:</p> <p>Right-click on the computeTest.Test project within the solution explorer and click Set as Startup Project. Next, use the Debug-&gt;Start (F5) or Debug-&gt;Start without Debugging (Ctrl+F5) menu items to begin running the tests.</p> <p>To view additional details on the test, we can double click on it to open up the AddTest() Results:</p> <p>Please note that the message in the assert statement does not appear for a "passing" test. It appears only when a test fails along with "Expected" and "Actual" values. Lets assume that by mistake (even though its highly unlikely) we have put total=x*y instead of x+y in source code file. Let's try to run the same test and see the results:</p> <p>How to do a Web testing for a login page 1. Create a login web page.</p> <p>Create a class dbaccess.cs inside the project. Create a method dbConnect() to connect to the database, it will return true if successful. Create a method IsUserExits(sUsername,sPassword) to check wheater the user exists or not.</p> <p>Create the unit test case for dbConnect and IsUserExists</p> <p>Making a connection to the Database: In Test menu click on Windows &gt; Test View. In Test View, right Click on method name --&gt; Properties --&gt; Chose Data Connection String, Data Table Name and Data Access method as sequential or random.</p> <p>2. Creating a Test Project. We create the test project just as we would any VSTS unit testing project. The steps below outline the process. In order to successfully record a test, the website must be running.</p> <p>1. Right-click the solution and click Add Project.2. Choose the programming language and select the Test node.</p> <p>3. Name the project Logintest.Test</p> <p>There is nothing specific about creating a project that defines it as a Web test project. Instead, the test files added to the project are specifically Web test files rather than another test file type (unit test, load test, manual test, generic test, and so on). The next step, therefore, is to add a Web test case. Since we are not going to use any of the other types of test files added to a test project, these can be deleted.</p> <p>1. Right-click the project, click Add, and then click Web Test. This opens up abrowser with a special Web Test Recorder explorer bar.</p> <p>Recording a Web test case</p> <p>2. On the address bar, enter the URL of the login web page, including the portselected by the ASP.NET Development Server. Browsing to this location will be recorded in the Web Test Recorder explorer bar as would any other URLs that are entered.</p> <p>3. Enter the user name and password that were added earlier. Upon clicking theLogin button, another entry will be recorded, along with the form post parameters. That way, when the test is run, the same data will automatically be sent. Even the X and Y coordinates of where the button was clicked are saved as part of the test, since these are also submitted as part of the request. 4. Add additional steps to the test by logging out of the site and then reattempting the login with invalid credentials. 5. Once the desired tests have been recorded, close the browser windows and save the test. Automatically, the project will now include the Web test case file along with each of the recorded requests.</p> <p>Viewing a recorded Web test case Selecting any of the nodes within the WebTest tree will allow you to modify the data inside the Properties window Running a Web Test Case After recording a test we are ready to begin executing it. To execute all the tests within a project, simply run the project. This will open up the Test Results windows and mark each test as pending while it is in progress and Passed/Failed once execution completes. Request Rules Although checking for valid hyperlinks on a response page is a useful feature, it is not sufficient in validating that the page is functioning correctly. For example, upon entering valid credentials, the Web test needs to verify that the login was successful. Similarly, when the credentials are invalid, we need to check that an appropriate error message is displayed on the page. To support this, each Web request can include extraction rules and validation rules. Extraction Rules Extraction rules capture a response value so that at a later time the value can be used within a request. Rather than parsing the entire HTTP response manually, the extraction rules provide a means of focusing in on a particular data item within the response. The extracted data item can then be validated or used again in a subsequent post back. Our recorded example automatically added an extraction rule when we logged on. The rule is an ExtractHiddenFields rule whose data is posted back in the second request of the Web test case. During the subsequent request, this data is submitted back in a hidden field on the page. Other extraction rule options are ExtractAttributeValue, ExtractHttpHeader, ExtractRegularExpression, &amp; ExtractText.</p> <p>Validation Rules Validation rules allow the test writer to examine the entire HTTP response and verify that it is correct. For example, valid credentials should cause the welcome! message to appear in the HTML response. A validation rule that checks for these items in the response should be added. The validation rules verify that this text appears somewhere within the response body.</p> <p>If a particular rule fails, the request will be marked as failed, and the Details tab will provide an explanation for what failed.</p> <p>This type of validation rule is a ValidationRuleFindText. It searches the entire response body, looking for the specified text. In order to handle complex searching, regular expressions are supported as part of ValidationRuleFindText. In addition to ValidationRuleFindText, built-in validation rules include Validatio...</p>