View
10
Download
0
Category
Preview:
Citation preview
UnitTesting
Hans-PetterHalvorsen,M.Sc.
Contents
1.WhatisTesting?– ShortIntroductiontoTesting
2.WhatisUnitTesting?3. UnitTestinginVisualStudio
IntroductiontoTesting
Hans-PetterHalvorsen,M.Sc.
RequirementsAnalysis
Design
Implementation
Testing
Maintenance
PlanningDeployment
SRS
SDD
STD
Code
InstallationGuides
UserGuides
GanttChart
withERDiagram,UMLDiagrams,CADDrawings
TestDocumentation
SoftwareRequirementsSpecifications
SoftwareDesignDocumentsSystemDocumentation
SoftwareTestPlan(STP)
ProjectPlanning
End-UserDocumentation
SystemDocumentation
SoftwareTestDocumentation
SDPSoftwareDevelopment
Plan
GanttChart
TheSoftwareDevelopment
Lifecycle(SDLC)
WhyFindBugsearly?
SoftwareDevelopmentLifeCycle(SDLC)
ValidationTesting DefectTesting
Testing
DemonstratetotheDeveloperandtheCustomerthattheSoftwaremeetsitsRequirements.
I.Sommerville,SoftwareEngineering,10ed.:Pearson,2015.
CustomSoftware:Thereshould beatleastonetestforeveryrequirement intheSRSdocument.GenericSoftware:Thereshould betestsforallofthesystemfeaturesthatwillbeincluded intheproductrelease.
Find inputsorinput sequenceswherethebehaviorofthesoftwareisincorrect,undesirable,ordoesnotconformtoitsspecifications.Thesearecausedbydefects(bugs) inthesoftware.
TestCategoriesBlack-boxvs.White-boxTesting
White-boxTesting:Youneedtohaveknowledgeofhow(DesignandImplementation)thesystemisbuilt
Black-boxTesting:Youneednoknowledgeofhowthesystemiscreated.
TypicallydonebyDevelopers,etc
LevelsofTesting
UnitTesting
IntegrationTesting
SystemTesting
AcceptanceTesting
Anymodule,program,objectseparatelytestable
Interfacebetweencomponents; interactionswithothersystems(OS,HW,etc)
Thebehaviorofthewholeproduct(system)asdefinedbythescopeoftheproject
Istheresponsibility ofthecustomer– ingeneral.Thegoalistogainconfidence inthesystem;especiallyinitsnon-functional characteristics
LevelsofTestingUnitTesting:Testeachpartsindependentlyandisolated
IntegrationTesting:Makesurethatdifferentpiecesworktogether.TesttheInterfacesbetweenthedifferentpieces.Interactionwithothersystems(Hardware,OS,etc.)
SystemTesting:Testthewholesystem
RegressionTesting:Testthatitstillworksafterachangeinthecode,i.e.,runallUnitTests,etc.
LevelsofTesting
UnitTesting
RegressionTesting
IntegrationTesting
System/ValidationTesting
AcceptanceTesting
Start
Finish
Requirements&DesignStartDevelopment
UnitTestsarewrittenbytheDevelopersaspartoftheProgramming.EachpartisdevelopedandUnittestedseparately(EveryClassandMethod inthecode)
TheCustomerneeds totestandapprove thesoftwarebeforehecantakeitintouse.FAT/SAT.
SystemtestingistypicallyBlack-boxTeststhatvalidatetheentiresystemagainstitsrequirements, i.eCheckingthatasoftwaresystemmeetsthespecifications
Integrationtestingmeansthesystemisputtogetherandtestedtomakesureeverythingworkstogether.
Regressiontestingistestingthesystemtocheckthatchangeshavenot“broken”previouslyworkingcode.BothManually&Automatically(Re-runUnitTests)
UnitTesting
Hans-PetterHalvorsen,M.Sc.
WhatareUnitTests• UnitTesting(orcomponenttesting)referstoteststhatverifythefunctionalityofaspecificsectionofcode,usuallyatthefunctionlevel.
• Inanobject-orientedenvironment,thisisusuallyattheclassandmethodslevel.
• UnitTestsaretypicallywrittenbythedevelopersaspartoftheprogramming
• Automaticallyexecuted(e.g.,VisualStudioandTeamFoundationServerhavebuilt-infunctionalityforUnitTesting)
TestDrivenDevelopment(TDD)• CodingandTestingaredoneinparallel• TheTestsarenormallywrittenbeforetheCode• IntroducedaspartofeXremeProgramming(XP)(anAgilemethod)
• UnitTestsareimportantpartofSoftwareDevelopmenttoday– eitheryouareusingTDDornot
UnitTestsFrameworksUnitTestsFrameworkareusuallyintegratedwiththeIDE• VisualStudioUnitTestFramework.UnitTestsarebuilt intoVisualStudio (noadditional
installationneeded)Others:• JUnit (Java)
– JUnitisaunittestingframeworkfortheJavaprogramminglanguage.• NUnit (.NET)
– NUnit isanopensourceunittestingframeworkforMicrosoft.NET.ItservesthesamepurposeasJUnitdoes intheJavaworld
• PHPUnit (PHP)• LabVIEWUnitTestFrameworkToolkit• etc.
Allofthemworkinthesamemanner– butwewillusetheVisualStudioUnitTestFramework
http://en.wikipedia.org/wiki/Visual_Studio_Unit_Testing_Framework
BasicConceptinUnitTesting
...
Assert.AreEqual(expected, actual, 0.001, ”Test failed because...");
ThebasicconceptinUnitTestingistoCompare theresultswhenrunningtheMethodswithsomeInputData(“Actual”)withsomeKnownResults(“Expected”)
Example:
CompareErrormargin Errormessageshown if
theTestfails
AllUnitTestsFrameworkhavetheAssertClass
TheAssertClasscontainsdifferentMethods thatcanbeusedinUnitTesting
UnitTests– BestPractice• AUnitTestmustonlydoonething• UnitTestmustrunindependently• UnitTestsmustnotbedependontheenvironment• TestFunctionalityratherthanimplementation• Testpublicbehavior;privatebehaviorrelatestoimplementation
details• AvoidtestingUIcomponents• UnitTestsmustbeeasytoreadandunderstand• CreaterulesthatmakesureyouneedtorunUnitTests(andthey
needtopass)beforeyouareallowedtoCheck-inyourCodeintheSourceCodeControlSystem
http://www.uio.no/studier/emner/matnat/ifi/INF5530
UnitTestinginVisualStudio
Hans-PetterHalvorsen,M.Sc.
UnitTestinginVisualStudio• VisualStudiohavebuilt-infeaturesforUnitTesting
• Weneedtoincludea“TestProject”inourSolution
TestMethodRequirements
Atestmethodmustmeetthefollowingrequirements:• Themethodmustbedecoratedwiththe[TestMethod]attribute.
• Themethodmustreturnvoid.• Themethodcannothaveparameters.
Example
Hans-PetterHalvorsen,M.Sc.
UnitTestinginVisualStudio
ConverttoFahrenheit
𝑇" =95𝑇& + 32
AsimplesketchoftheUserInterface:
ConversionFormula:
CreatethefollowingApplication (e.g.,WinForm ApporASP.NETApp)
Celsius:22 ℃ Convert 71,6 ℉
Fahrenheit:
UserInterface
CreateyourGUI
Add Class
Class
𝑇" =95𝑇& + 32
public class TemperatureConvert{
public double CelciusToFahrenheit(double Tc){
double Tf;
Tf = 9/5 * Tc + 32;
return Tf;}
}
CreateyourCode
using System;using System.Windows.Forms;
namespace TemperatureApp{
public partial class Form1 : Form{
public Form1(){
InitializeComponent();}
private void btnConvert_Click(object sender, EventArgs e){
TemperatureConvert temperature = new TemperatureConvert();
double temperatureFahrenheit;double temperatureCelcius;
temperatureCelcius = Convert.ToDouble(txtCelsius.Text);
temperatureFahrenheit = temperature.CelciusToFahrenheit(temperatureCelcius);
txtFahrenheit.Text = temperatureFahrenheit.ToString();
}}
}
TestApplication
𝑇" =95𝑇& + 32
𝑇" =95 , 22 + 32
=71.6WegetwrongAnswer!
CreateUnitTestProject
Youhavenow2ProjectsinyourSolutionExplorer
AddReferencetotheCodeunderTest
CreatetheUnitTestCode
CreatetheUnitTestCode
using Microsoft.VisualStudio.TestTools.UnitTesting;using TemperatureApp;
namespace UnitTestTemperature{[TestClass]public class UnitTestTempConvert{[TestMethod]public void TestFahrenheitConversion(){TemperatureConvert temperature =new TemperatureConvert();doubletemperatureCelcius =22;doubletemperatureFahrenheitActual;doubletemperatureFahrenheitExpected =71.6;
temperatureFahrenheitActual =temperature.CelciusToFahrenheit(temperatureCelcius);
Assert.AreEqual(temperatureFahrenheitExpected,temperatureFahrenheitActual,0.001,"Temperature conversionnotcorrectly");
}}
}
TestExplorer
StartRunningtheUnitTest
TestResults
Debuggingpublic class TemperatureConvert{
public double CelciusToFahrenheit(double Tc){
double Tf;
Tf = 9/5 * Tc + 32;
return Tf;
}
}
𝑇" =95𝑇& + 32
ProbablyErrorinFormula?Whatiswrong?
FixingBugspublic class TemperatureConvert
{
public double CelciusToFahrenheit(double Tc){
double Tf;
Tf = Tc*9/5 + 32;
return Tf;
}
}
𝑇" =95𝑇& + 32
Re-runUnitTest
EverythingWorks!TheTestPassed!
CheckingCodeCoverage
CodeCoverage• Codecoverageisameasureusedinsoftwaretesting.Itdescribes
thedegreetowhichthesourcecodeofaprogramhasbeentested.
• Dependingontheinputarguments,differentpartsofthecodewillbeexecuted.UnitTestsshouldbewrittentocoverallpartsofthecode.
CodeCoverageResults
InthiscasetheUnitTestcovered100%ofthecode.IfweuseIf…Else…orsimiliar,wetypicallyneedtowriteUnitTestforeachIf…Else…inordertocoveralltheCode
Hans-PetterHalvorsen,M.Sc.
UniversityCollegeofSoutheastNorwaywww.usn.no
E-mail:hans.p.halvorsen@hit.noBlog:http://home.hit.no/~hansha/
Recommended