Download - Create Unit Tests
![Page 1: Create Unit Tests](https://reader031.vdocuments.us/reader031/viewer/2022021500/586a10f81a28abce0c8b5442/html5/thumbnails/1.jpg)
CreateUnitTests
Hans-PetterHalvorsen,M.Sc.
StepbystepExercises
![Page 2: Create Unit Tests](https://reader031.vdocuments.us/reader031/viewer/2022021500/586a10f81a28abce0c8b5442/html5/thumbnails/2.jpg)
LevelsofTestingUnitTesting:Testeachpartsindependentlyandisolated
IntegrationTesting:Makesurethatdifferentpiecesworktogether.TesttheInterfacesbetweenthedifferentpieces.Interactionwithothersystems(Hardware,OS,etc.)
SystemTesting:Testthewholesystem
RegressionTesting:Testthatitstillworksafterachangeinthecode
![Page 3: Create Unit Tests](https://reader031.vdocuments.us/reader031/viewer/2022021500/586a10f81a28abce0c8b5442/html5/thumbnails/3.jpg)
WhatareUnitTests?• UnitTesting(orcomponenttesting)referstoteststhatverifythefunctionalityofaspecificsectionofcode,usuallyatthefunctionlevel.
• Inanobject-orientedenvironment,thisisusuallyattheclassandmethodslevel.
• UnitTestsaretypicallywrittenbythedevelopersaspartoftheprogramming
• Itisalsoknownascomponenttesting.• TypicallyAutomaticallyexecuted(e.g.,VisualStudioandTeam
FoundationServerhavebuilt-infunctionalityforUnitTesting
Theory
http://en.wikipedia.org/wiki/Unit_testing
![Page 4: Create Unit Tests](https://reader031.vdocuments.us/reader031/viewer/2022021500/586a10f81a28abce0c8b5442/html5/thumbnails/4.jpg)
TestDrivenDevelopment(TDD)• CodingandTestingaredoneinparallel• TheTestsarenormallywrittenbeforetheCode• IntroducedaspartofeXremeProgramming(XP)(anAgilemethod)
• UnitTestsareimportantpartofSoftwareDevelopmenttoday– eitheryouareusingTDDornot
Theory
![Page 5: Create Unit Tests](https://reader031.vdocuments.us/reader031/viewer/2022021500/586a10f81a28abce0c8b5442/html5/thumbnails/5.jpg)
UnitTestsFrameworksUnitTestsFrameworkareusuallyintegratedwiththeIDE• VisualStudioUnitTestFramework.UnitTestsarebuilt intoVisualStudio (noadditional
installationneeded)Others:• JUnit (Java)
– JUnitisaunittestingframeworkfortheJavaprogramminglanguage.• NUnit (.NET)
– NUnit isanopensourceunittestingframeworkforMicrosoft.NET.ItservesthesamepurposeasJUnitdoes intheJavaworld
• PHPUnit (PHP)• LabVIEWUnitTestFrameworkToolkit• etc.Allofthemworkinthesamemanner– butwewillusetheVisualStudioUnitTestFramework
Theory
http://en.wikipedia.org/wiki/Visual_Studio_Unit_Testing_Framework
![Page 6: Create Unit Tests](https://reader031.vdocuments.us/reader031/viewer/2022021500/586a10f81a28abce0c8b5442/html5/thumbnails/6.jpg)
ExercisesVisualStudio:1. CreateUnitTestsinVisualStudio2. CodeCoverage
Project:4. CreateUnitTestsforyourCodeinyourProject
![Page 7: Create Unit Tests](https://reader031.vdocuments.us/reader031/viewer/2022021500/586a10f81a28abce0c8b5442/html5/thumbnails/7.jpg)
CreateUnitTestsinVisualStudio• VisualStudiohavebuilt-infeaturesforUnitTesting
• InthisexamplewewillcreateasimpleClassLibrary
• ThenwewillcreateaTestClassinordertotestourcode(includeaTestProjectinourSolution)
http://msdn.microsoft.com/en-us/library/ms182532.aspx
![Page 8: Create Unit Tests](https://reader031.vdocuments.us/reader031/viewer/2022021500/586a10f81a28abce0c8b5442/html5/thumbnails/8.jpg)
CreatetheCodeyouwanttoTest
Bank
ClassLibrary
CreateNewProject
StepbystepExample
![Page 9: Create Unit Tests](https://reader031.vdocuments.us/reader031/viewer/2022021500/586a10f81a28abce0c8b5442/html5/thumbnails/9.jpg)
9
Rename“Class1.cs”->“BankAccount.cs”
using System;namespace BankAccountNS{
public class BankAccount{
private string m_customerName;
private double m_balance;
public BankAccount(string customerName, double balance){
m_customerName = customerName;m_balance = balance;
}
public double Balance{
get { return m_balance; }}
public void Debit(double amount){
if (amount > m_balance){
throw new ArgumentOutOfRangeException("amount");}
if (amount < 0){
throw new ArgumentOutOfRangeException("amount");}
m_balance += amount;}
}}
CreatethefollowingClassandMethods:
ThenBuildtheProjecttomakesureitworkswithouranyerrors.
![Page 10: Create Unit Tests](https://reader031.vdocuments.us/reader031/viewer/2022021500/586a10f81a28abce0c8b5442/html5/thumbnails/10.jpg)
AddNewProject:UnitTestProject
CreateaproperNameforyourProject
![Page 11: Create Unit Tests](https://reader031.vdocuments.us/reader031/viewer/2022021500/586a10f81a28abce0c8b5442/html5/thumbnails/11.jpg)
11
YourSolutionshouldnowhave2ProjectsAddReferencetotheCodeunderTest
![Page 12: Create Unit Tests](https://reader031.vdocuments.us/reader031/viewer/2022021500/586a10f81a28abce0c8b5442/html5/thumbnails/12.jpg)
CreateTestClass“BankAccountTests.cs”WeneedaTestClassforverifying the“BankAccount”class.WecanusetheUnitTest1.csthatwasgeneratedbytheprojecttemplate,butweshouldgivethefileandclassmoredescriptivenames.Wecando thatinonestepbyrenaming thefileinSolutionExplorer.
using System;using Microsoft.VisualStudio.TestTools.UnitTesting;
using BankAccountNS;
namespace BankTest{
[TestClass]public class BankAccountTests{
[TestMethod]public void TestMethod1(){}
}}
Makesuretoaddreferencetothecodeunder test
BankAccountTests.cs
Note!TheTestClassshouldbelabeled[TestClass]andtheTestMethodsneedtobelabeled[TestMethod]
ReferencetoTestFramework
![Page 13: Create Unit Tests](https://reader031.vdocuments.us/reader031/viewer/2022021500/586a10f81a28abce0c8b5442/html5/thumbnails/13.jpg)
TestMethodRequirementsAtestmethodmustmeetthefollowingrequirements:• Themethodmustbedecoratedwiththe[TestMethod]attribute.• Themethodmustreturnvoid.• Themethodcannothaveparameters.
Theory
![Page 14: Create Unit Tests](https://reader031.vdocuments.us/reader031/viewer/2022021500/586a10f81a28abce0c8b5442/html5/thumbnails/14.jpg)
BasicConceptinUnitTesting
...
Assert.AreEqual(expected, actual, 0.001, ”Test failed because...");
ThebasicconceptinUnitTestingistoCompare theresultswhenrunningtheMethodswithsomeInputData(“Actual”)withsomeKnownResults(“Expected”)
Example:
CompareFeilmargin Feilmelding somvises
hvistestenfeilerAssert:Hevde/bedyre
AllUnitTestsFrameworkhavetheAssertClass
TheAssertClasscontainsdifferentMethods thatcanbeusedinUnitTesting
Theory
![Page 15: Create Unit Tests](https://reader031.vdocuments.us/reader031/viewer/2022021500/586a10f81a28abce0c8b5442/html5/thumbnails/15.jpg)
Assert:Hevde/bedyre
![Page 16: Create Unit Tests](https://reader031.vdocuments.us/reader031/viewer/2022021500/586a10f81a28abce0c8b5442/html5/thumbnails/16.jpg)
CreatethefirstTestMethodWewillwriteunittestmethods toverify thebehaviorofthe“Debit”methodofthe“BankAccount”class
[TestMethod]public void Debit_WithValidAmount_UpdatesBalance(){
// arrangedouble beginningBalance = 11.99;double debitAmount = 4.55;double expected = 7.44;
BankAccount account = new BankAccount("Mr. Bryan Walton", beginningBalance);
// actaccount.Debit(debitAmount);
// assertdouble actual = account.Balance;
Assert.AreEqual(expected, actual, 0.001, "Account not debited correctly");}
Debit_WithValidAmount_UpdatesBalance()CreatethefollowingMethodinthe“BankAccountTests.cs”Class:
Expected=Balance- debitAmount=11.99- 4.55=7.44
![Page 17: Create Unit Tests](https://reader031.vdocuments.us/reader031/viewer/2022021500/586a10f81a28abce0c8b5442/html5/thumbnails/17.jpg)
RunningtheUnitTestusingthe“TestExplorer”
17
IfTestExplorerdoesnotappearafterasuccessfulbuild, chooseTest onthemenu, thenchooseWindows,andthenchooseTestExplorer.
Attheendofthetestrun,thebarturnsgreenifallthetestmethodspass,orredifanyofthetestsfail.
Inthiscase,thetestdoesfail.Thetestmethod ismoved totheFailedTests.group.
Selectthemethod inTestExplorertoviewthedetailsatthebottomofthewindow.
![Page 18: Create Unit Tests](https://reader031.vdocuments.us/reader031/viewer/2022021500/586a10f81a28abce0c8b5442/html5/thumbnails/18.jpg)
CanyoufindtheBugbasedontheTestResults?
![Page 19: Create Unit Tests](https://reader031.vdocuments.us/reader031/viewer/2022021500/586a10f81a28abce0c8b5442/html5/thumbnails/19.jpg)
AnalyzingtheTestResults
• Thetestresultcontainsamessagethatdescribesthefailure.• FortheAreEqualsmethod,messagedisplaysyouwhatwasexpected(the
(Expected<XXX>parameter)andwhatwasactuallyreceived(theActual<YYY> parameter).
• Wewereexpectingthebalancetodeclinefromthebeginningbalance,butinsteadithasincreasedbytheamountofthewithdrawal.
• AreexaminationoftheDebitcodeshowsthattheunittesthassucceededinfindingabug.Theamountofthewithdrawalisaddedtotheaccountbalancewhenitshouldbesubtracted.
m_balance += amount;
![Page 20: Create Unit Tests](https://reader031.vdocuments.us/reader031/viewer/2022021500/586a10f81a28abce0c8b5442/html5/thumbnails/20.jpg)
CorrectiontheBugm_balance += amount; m_balance -= amount;->
ReruntheTestInTestExplorer, chooseRunAll torerun thetest.Thered/greenbarturnsgreen,andthetestismovedtothePassedTests group.
![Page 21: Create Unit Tests](https://reader031.vdocuments.us/reader031/viewer/2022021500/586a10f81a28abce0c8b5442/html5/thumbnails/21.jpg)
YouarefinishedwiththeExercise
![Page 22: Create Unit Tests](https://reader031.vdocuments.us/reader031/viewer/2022021500/586a10f81a28abce0c8b5442/html5/thumbnails/22.jpg)
CodeCoverage• Codecoverageisameasureusedinsoftwaretesting.Itdescribes
thedegreetowhichthesourcecodeofaprogramhasbeentested.
• Dependingontheinputarguments,differentpartsofthecodewillbeexecuted.UnitTestsshouldbewrittentocoverallpartsofthecode.
![Page 23: Create Unit Tests](https://reader031.vdocuments.us/reader031/viewer/2022021500/586a10f81a28abce0c8b5442/html5/thumbnails/23.jpg)
RunCodeCoverage• Weseethatourtestonlycoverabout43%
ofthecodeinour“Debit”Method.• ThisisbecausetheMethodcontainsif
sentences• Weshould improvetheUnitTestingsothat
wecovermoreofthecode.
=>TrytoImprovetheUnitTestingsoitcovers100%ofthecodeintheDebitMethod
![Page 24: Create Unit Tests](https://reader031.vdocuments.us/reader031/viewer/2022021500/586a10f81a28abce0c8b5442/html5/thumbnails/24.jpg)
YouarefinishedwiththeExercise
![Page 25: Create Unit Tests](https://reader031.vdocuments.us/reader031/viewer/2022021500/586a10f81a28abce0c8b5442/html5/thumbnails/25.jpg)
MoreaboutUnitTestinginVisualStudio
http://msdn.microsoft.com/en-us/library/dd264975.aspx
Ifyouwanttolearnmore,visitthefollowing:
VerifyingCodebyUsingUnitTests:
Microsoft.VisualStudio.TestTools.UnitTestingTheUnitTestingnamespace,whichprovidesattributes,exceptions,asserts,andotherclassesthatsupportunittesting.Microsoft.VisualStudio.TestTools.UnitTesting.WebTheUnitTesting.Webnamespace,whichextendstheUnitTestingnamespacebyprovidingsupport forASP.NETandWebserviceunittests.
![Page 26: Create Unit Tests](https://reader031.vdocuments.us/reader031/viewer/2022021500/586a10f81a28abce0c8b5442/html5/thumbnails/26.jpg)
ProjectAssignment• CreateUnitTestsforsomepartsofyourCodeinyourProject
![Page 27: Create Unit Tests](https://reader031.vdocuments.us/reader031/viewer/2022021500/586a10f81a28abce0c8b5442/html5/thumbnails/27.jpg)
YouarefinishedwiththeExercise
![Page 28: Create Unit Tests](https://reader031.vdocuments.us/reader031/viewer/2022021500/586a10f81a28abce0c8b5442/html5/thumbnails/28.jpg)
Poenget er ikke å luretestene,menå sørge foratkoden er feilfri!
![Page 29: Create Unit Tests](https://reader031.vdocuments.us/reader031/viewer/2022021500/586a10f81a28abce0c8b5442/html5/thumbnails/29.jpg)
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
Theory
![Page 30: Create Unit Tests](https://reader031.vdocuments.us/reader031/viewer/2022021500/586a10f81a28abce0c8b5442/html5/thumbnails/30.jpg)
References• I.Sommerville,SoftwareEngineering:Pearson,2015.• Wikipedia:UnitTesting:http://en.wikipedia.org/wiki/Unit_test• Wikipedia:JUnit:http://en.wikipedia.org/wiki/JUnit• Wikipedia:NUnit:http://en.wikipedia.org/wiki/NUnit• CreateUnitTestsinVisualStudio:
http://msdn.microsoft.com/en-us/library/ms182532.aspx• CourseatUiO:FoundationsofSoftwareTesting:
http://www.uio.no/studier/emner/matnat/ifi/INF5530
![Page 31: Create Unit Tests](https://reader031.vdocuments.us/reader031/viewer/2022021500/586a10f81a28abce0c8b5442/html5/thumbnails/31.jpg)
Hans-PetterHalvorsen,M.Sc.
UniversityCollegeofSoutheastNorwaywww.usn.no
E-mail:[email protected]:http://home.hit.no/~hansha/