Os Testes são cada vez mais uma necessidade nos projectos de desenvolvimento de software... Sejam eles unitários, de carga ou de "User Interface", uma boa framework de testes ajuda a resolver os problemas mais cedo, de forma mais eficaz e mais barata.
No final da sessão vamos perceber não só para que servem, como são feitos e como o Visual Studio 2010 pode ajudar.
8. Lack of software quality cost US businesses $59B / year.
9. Bugs account for 55% of downtime Source: Standish Group, 2006 Third Quarter Research Report, CHAOS Research Results
10. Have you heard any of these? “my testers are spending too long testing the same thing” “tooling is expensive (time, licenses, people)” “the developers say the defects are useless” “when is my software ready to ship?” “developers and testers work in silos and don’t communicate/speak the same language” “we have a changed requirement, what do I need to test?”
12. What if you could… reduce the time it takes to determine the root cause of a bug enable users to easily run acceptance tests and track their results reduce the time it takes to configure and manage test environments reduce the time it takes to verify the status of a reported bug fix repair a bug without having to reproduce it
13. software bugs cost the US economy an estimated $59.5 billion every year on average professional coders make 100 to 150 errors in every 1000 lines of code they write last year, canceled projects cost firms $67 billion; overruns on the other projects racked up another $21billion
15. USS Yorktown, SmartShip crew member entered 0 in a data entry field, caused a “divide by 0” error that shut down propulsion dead in the water for 2hrs 45mins
16. Ariane 5 Flight 501 re-used code from ariane 4, but took a different flight path because of different booster design conversation from 64bit float to 16bit signed int caused overflow (exception handler was disabled for perf reasons) cost: > $370 million @ 1996 prices
17. F-22 Raptor deploying overseas to japan the first time crossed international dateline, computers crashed losing all navigation and communications systems clear weather allowed them to follow tankers back to hawaii Raptor is likely the most advanced manned aircraft that will ever fly…
29. Test Manager 2010 UML Modeling Manual Testing Layer Diagram Load Testing Web Testing Test Case Management IntelliTrace™ Architecture Explorer Logical Class Designer Cloud Development Office Development Windows Development New WPF Editor Customizable IDE Multi-core Development Silverlight Tools Web Development SharePoint Development Generate from Usage Static Code Analysis Database Deployment Code Metrics Database Unit Testing Test Data Generation Test Impact Analysis UI Test Automation Code Coverage Performance Profiling Database Change Mgmt Fast Forward for Manual Testing
38. Unit Test – Definition A unit test is a piece of code written by a developer that exercises a very small, specific area of functionality of the code being tested. “Program testing can be used to show the presence of bugs, but never to show their absence!” EdsgerDijkstra, [1972]
46. Unit Testing Some Facts Tests are specific pieces of code Unit testing framework is needed Visual Studio Team Test NUnit MbUnit Unit tests are written by developers, not by QA engineers Unit tests are released into the code repository along with the code they test
47. Unit Testing – More Facts All classes should be tested Test anything that could have bugs All methods should be tested Trivial code may be omitted E.g. property getters and setters Ideally all unit tests should pass before check-in into the source control repository
48. Why Unit Tests? Unit tests dramatically decrease the number of defects in the code Unit tests improve design Unit tests are good documentation Unit tests reduce the cost of change Unit tests allow refactoring Unit tests decrease the defect-injection rate due to refactoring / changes
50. Unit Testing Approaches "Code and Test" approach Classical approach "Test First" approach Test driven development (TDD)
51. Code and Test Approach Write code Write unit test Run and succeed Time flow
52. Create a testlist Pick а test Compile and fail Write enough code to compile Run test and fail Write code to pass test Test Driven Development Write test Time flow Remove duplication
53. Why Test Driven Development? Helps find design issues early and avoids rework Writing code to satisfy a test is a focused activity – less chance of error Tests will be a more comprehensive than when written after code
55. Unit Testing Frameworks JUnit The first popular unit testing framework Based on Java Similar frameworks have been developed for a broad range of computer languages NUnit – for C# and all .NET languages cppUnit, jsUnit, PhpUnit, PerlUnit, ... Visual Studio Team Test (VSTT) Developed by Microsoft, integrated in VS
56. Visual Studio Team Test – Features Team Test (TT) is very well integrated with Visual Studio Create test projects and unit tests Execute unit tests View execution results View code coverage Located in the assembly Microsoft.VisualStudio.QualityTools.UnitTestFramework.dll
64. VSTT – Assertions Assertions check condition and throw exception if condition is not satisfied Comparing values AreEqual(expected value, calculated value [,message]) – compare two values for equality Comparing objects AreSame(expected object, current object [,message])– compare object references
65. VSTT – Assertions (2) Checking for null value IsNull(object [,message]) IsNotNull(object [,message]) Conditions IsTrue(condition) IsFalse(condition) Forced test fail Fail(message)
66. The 3A Pattern Arrange all necessary preconditions and inputs Act on the object or method under test Assert that the expected results have occurred [TestMethod] public void TestDeposit() { BanckAccount account = new BanckAccount(); account.Deposit(125.0); account.Deposit(25.0); Assert.AreEqual(150.0, account.Balance, "Balance is wrong."); }
67. VSTT – Example public class Account { private decimal balance; public void Deposit(decimal amount) { this.balance += amount; } public void Withdraw(decimal amount) { this.balance -= amount; } public void TransferFunds( Account destination, decimal amount) { ... } public decimal Balance { ... } }
68. VSTT – Example (2) using Microsoft.VisualStudio.TestTools.UnitTesting; [TestClass] public class AccountTest { [TestMethod] public void TransferFunds() { Account source = new Account(); source.Deposit(200.00M); Account dest = new Account(); dest.Deposit(150.00F); source.TransferFunds(dest, 100.00F); Assert.AreEqual(250.00F, dest.Balance); Assert.AreEqual(100.00F, source.Balance); } }
72. Naming Standards for Unit Tests The test name should express a specific requirement that is tested Usually prefixed with [Test] E.g. TestAccountDepositNegativeSum() The test name should include Expected input or state Expected result output or state Name of the tested method or class
73. Naming Standards for Unit Tests Example Given the method: with requirement to ignore numbers greater than 100 in the summing process The test name should be: Sum_NumberIgnoredIfGreaterThan100 public int Sum(params int[] values)
74. When Should a Test be Changed or Removed? Generally, a passing test should never be removed These tests make sure that code changes don’t break working code A passing test should only be changed to make it more readable When failing tests don’t pass, it usually means there are conflicting requirements
75. When Should a Test be Changed or Removed? (2) Example: New features allows negative numbers [ExpectedException(typeof(Exception), "Negatives not allowed")] void Sum_FirstNegativeNumberThrowsException() { Sum (-1,1,2); }
76. When Should a Test be Changed or Removed?(3) New developer writes the following test: Earlier test fails due to a requirement change void Sum_FirstNegativeNumberCalculatesCorrectly() { int sumResult = sum(-1, 1, 2); Assert.AreEqual(2, sumResult); }
77. When Should a Test be Changed or Removed? (4) Two course of actions: Delete the failing test after verifying if it’s valid Change the old test: Either testing the new requirement Or test the older requirement under new settings
78. Tests Should Reflect Required Reality What’s wrong with the following test? A failing test should prove that there is something wrong with the production code Not with the unit test code int Sum(int a, int b) –> returns sum of a and b public void Sum_AddsOneAndTwo() { int result = Sum(1,2); Assert.AreEqual(4, result, "Bad sum"); }
79. What Should Assert Messages Say? Assert message in a test is one of the most important things Tells us what we expected to happen but didn’t, and what happened instead Good assert message helps us track bugs and understand unit tests more easily Example: "Withdrawal failed: accounts are not supposed to have negative balance."
80. What Should Assert Messages Say? (2) Express what should have happened and what did nothappen “Verify() did not throw any exception” “Connect() did not open the connection before returning it” Do not: Provide empty or meaningless messages Provide messages that repeat the name of the test case
81. Avoid Multiple Asserts in a Single Unit Test void Sum_AnyParamBiggerThan1000IsNotSummed() { Assert.AreEqual(3, Sum(1001, 1, 2); Assert.AreEqual(3, Sum(1, 1001, 2); Assert.AreEqual(3, Sum(1, 2, 1001); } Avoid multiple asserts in a single test case If the first assert fails, the test execution stops for this test case Affect future coders to add assertions to test rather than introducing a new one
82. Unit Testing – The Challenge The concept of Unit Testing has been around for many years New methodologies in particular XP, have turned unit testing into a cardinal foundation of software development Writing good & effective Unit Tests is hard! This is where supporting integrated tools and suggested guidelines enter the picture The ultimate goal is tools that generate unit tests automatically
83.
84. Load tests run software unit tests, database unit tests, and web performance tests
96. Web Test Recorder Plugin WebTestRecorderPlugins Visual Studio Launches Internet Explorer RecorderListener Browser Recorder Wininet Recorder Merging Recorder Internet Explorer Visual Studio Recorder BHO Browser events Recorded Web Test Record events Browser Control Wininet Shim Recorder Result Wininet Record events Intercept s wininet calls Record events
97. Load Test Agent Architecture Test agents run tests and collect data Test agent #1 Test agent #2 Test agent #3 Test Agent Run Tests Visual Studio Ultimate 2010 Test Controller Target Server Collector Agent Asp.Net Profiler Test Controller manages test agents
101. Próximas reuniões presenciais 09/04/2011 - Abril (Coimbra) 16/04/2011 - Abril (Lisboa) 21/05/2011 - Maio (Lisboa) 18/06/2011 - Junho (Lisboa)Reserva estes dias na agenda! :)
102. Obrigado! Pedro Rosa http://pt.linkedin.com/in/pedrobarraurosa http://twitter.com/pedrorosa
Editor's Notes
These are some of the comments that we have heard from our customers. Are any of these being said by your testers?Broken down another way, can you answer these affirmatively?Do you know consistently when your software will ship?Are the defects created by your tester truly effective?No? <click to next>
All of the previous slides boils down to the fact that 68% of projects are challenged or FailNote that all of this is not due to testing, but good quality almost always ensures a successful release.According to Forrester Research, based on time, budget and delivering specified functionality 68% of projects never made it into production or were cancelled. The numbers tell the story with only 32% of projects being classified as successful with 44% being classed as challenged and 24% failed.The Standish Groups Extreme Chaos study tells a similar story with the average Cost overrun for projects being 45%, the average Time overrun at 63% and the average functionality delivered at 67%Considering that software development accounts for on average 25% of software spend for a company and is growing can organizations afford to continue to see these levels of failure? Identifying and addressing the root causes of software development failure makes business sense. Source: Extreme Chaos, The Standish Group International, Inc., 2000, 2004, 2006, 2009
Does this sound like a wish list? How much money is lost in the time that it takes to track down a bug?How much money is lost in the time it takes to isolate the differences between your development in test environments?
It is also important to understand where most testing happens in the spectrum of general testing to the more technical specialist testing.The Generalist Testers are usually professional testers with no coding background. Often these testers are experts in the business process or tool that is being developed. On the opposite side of the spectrum is the Specialist. This is a tester with strong coding skills.A fun side note: Microsoft’s testers are usually converted developers and tend to be on the specialist side of the graph.Black-box testing is a method of testing software that tests the functionality of an application as opposed to its internal structures or workings (see white-box testing). Specific knowledge of the application's code/internal structure and programming knowledge in general is not required. Test cases are built around specifications and requirements, i.e., what the application is supposed to do. It uses external descriptions of the software, including specifications, requirements, and design to derive test cases. These tests can be functional or non-functional, though usually functional. The test designer selects valid and invalid inputs and determines the correct output. There is no knowledge of the test object's internal structure.White-box testing (a.k.a. clear box testing, glass box testing, transparent box testing, or structural testing) is a method of testing software that tests internal structures or workings of an application as opposed to its functionality (black-box testing). An internal perspective of the system, as well as programming skills, are required and used to design test cases. The tester chooses inputs to exercise paths through the code and determine the appropriate outputs. It is analogous to testing nodes in a circuit, e.g. in-circuit testing (ICT). While white-box testing can be applied at the unit, integration and system levels of the software testing process, it is usually done at the unit level. It can test paths within a unit, paths between units during integration, and between subsystems during a system level test. Though this method of test design can uncover many errors or problems, it might not detect unimplemented parts of the specification or missing requirements. White-box test design techniques include: Control flow testing Data flow testing Branch testing Path testingAPI testing (application programming interface) – is a specific type of White Box testing of the application focusing on public and private APIs<Question to Audience>Looking at this spectrum, where does most testing happen today? <collect answers and click>Where do most testing tools target today? <collect answers and click>
This is the fully animated slide.
Let me drill down into the capabilities in each product. For a more extensive list of capabilities, please go to www.microsoft.com.vstudio.Microsoft Visual Studio 2010 Professional is the essential tool for basic development tasks to allow developers to implement their ideas easily. This includes core capabilities for Windows, Web, and Office development, along with new capabilities for Cloud and SharePoint development. There are also new tools for Silverlight and Multi-core development. With Visual Studio 2010 the IDE and editor were refreshed using Microsoft Windows Presentation Foundation.[CLICK]Microsoft Visual Studio 2010 Premium is a complete toolset for developers to deliver scalable, high quality applications. This includes support for offline database development, unit testing and change management, static code analysis, performance profiling and code coverage and code metrics. New capabilities including UI test automation (aka Coded UI Tests) and Test Impact Analysis are available in premium.[CLICK]Microsoft Visual Studio 2010 Ultimate is the comprehensive suite of application lifecycle management tools for teams to ensure quality results from design to deployment. This includes IntelliTrace – the new historical debugger which enables debugging events that ran previously on your machine, or another machine. Microsoft Test Manager 2010 is included in Ultimate enabling complete Test Case Management and test execution. Additionally the new architecture and modeling tools are included in Ultimate, including support for authoring UML diagrams (Activity, Use Case, Sequence, Component and Class diagrams are supported).[CLICK]