Top Banner
Create Unit Tests Hans-Petter Halvorsen, M.Sc. Step by step Exercises
31

Create Unit Tests

Jan 02, 2017

Download

Documents

trinhhanh
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Create Unit Tests

CreateUnitTests

Hans-PetterHalvorsen,M.Sc.

StepbystepExercises

Page 2: Create Unit Tests

LevelsofTestingUnitTesting:Testeachpartsindependentlyandisolated

IntegrationTesting:Makesurethatdifferentpiecesworktogether.TesttheInterfacesbetweenthedifferentpieces.Interactionwithothersystems(Hardware,OS,etc.)

SystemTesting:Testthewholesystem

RegressionTesting:Testthatitstillworksafterachangeinthecode

Page 3: Create Unit Tests

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

TestDrivenDevelopment(TDD)• CodingandTestingaredoneinparallel• TheTestsarenormallywrittenbeforetheCode• IntroducedaspartofeXremeProgramming(XP)(anAgilemethod)

• UnitTestsareimportantpartofSoftwareDevelopmenttoday– eitheryouareusingTDDornot

Theory

Page 5: Create Unit Tests

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

ExercisesVisualStudio:1. CreateUnitTestsinVisualStudio2. CodeCoverage

Project:4. CreateUnitTestsforyourCodeinyourProject

Page 7: Create Unit Tests

CreateUnitTestsinVisualStudio• VisualStudiohavebuilt-infeaturesforUnitTesting

• InthisexamplewewillcreateasimpleClassLibrary

• ThenwewillcreateaTestClassinordertotestourcode(includeaTestProjectinourSolution)

http://msdn.microsoft.com/en-us/library/ms182532.aspx

Page 8: Create Unit Tests

CreatetheCodeyouwanttoTest

Bank

ClassLibrary

CreateNewProject

StepbystepExample

Page 9: Create Unit Tests

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

AddNewProject:UnitTestProject

CreateaproperNameforyourProject

Page 11: Create Unit Tests

11

YourSolutionshouldnowhave2ProjectsAddReferencetotheCodeunderTest

Page 12: Create Unit Tests

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

TestMethodRequirementsAtestmethodmustmeetthefollowingrequirements:• Themethodmustbedecoratedwiththe[TestMethod]attribute.• Themethodmustreturnvoid.• Themethodcannothaveparameters.

Theory

Page 14: Create Unit Tests

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

Assert:Hevde/bedyre

Page 16: Create Unit Tests

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

RunningtheUnitTestusingthe“TestExplorer”

17

IfTestExplorerdoesnotappearafterasuccessfulbuild, chooseTest onthemenu, thenchooseWindows,andthenchooseTestExplorer.

Attheendofthetestrun,thebarturnsgreenifallthetestmethodspass,orredifanyofthetestsfail.

Inthiscase,thetestdoesfail.Thetestmethod ismoved totheFailedTests.group.

Selectthemethod inTestExplorertoviewthedetailsatthebottomofthewindow.

Page 18: Create Unit Tests

CanyoufindtheBugbasedontheTestResults?

Page 19: Create Unit Tests

AnalyzingtheTestResults

• Thetestresultcontainsamessagethatdescribesthefailure.• FortheAreEqualsmethod,messagedisplaysyouwhatwasexpected(the

(Expected<XXX>parameter)andwhatwasactuallyreceived(theActual<YYY> parameter).

• Wewereexpectingthebalancetodeclinefromthebeginningbalance,butinsteadithasincreasedbytheamountofthewithdrawal.

• AreexaminationoftheDebitcodeshowsthattheunittesthassucceededinfindingabug.Theamountofthewithdrawalisaddedtotheaccountbalancewhenitshouldbesubtracted.

m_balance += amount;

Page 20: Create Unit Tests

CorrectiontheBugm_balance += amount; m_balance -= amount;->

ReruntheTestInTestExplorer, chooseRunAll torerun thetest.Thered/greenbarturnsgreen,andthetestismovedtothePassedTests group.

Page 21: Create Unit Tests

YouarefinishedwiththeExercise

Page 22: Create Unit Tests

CodeCoverage• Codecoverageisameasureusedinsoftwaretesting.Itdescribes

thedegreetowhichthesourcecodeofaprogramhasbeentested.

• Dependingontheinputarguments,differentpartsofthecodewillbeexecuted.UnitTestsshouldbewrittentocoverallpartsofthecode.

Page 23: Create Unit Tests

RunCodeCoverage• Weseethatourtestonlycoverabout43%

ofthecodeinour“Debit”Method.• ThisisbecausetheMethodcontainsif

sentences• Weshould improvetheUnitTestingsothat

wecovermoreofthecode.

=>TrytoImprovetheUnitTestingsoitcovers100%ofthecodeintheDebitMethod

Page 24: Create Unit Tests

YouarefinishedwiththeExercise

Page 25: Create Unit Tests

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

ProjectAssignment• CreateUnitTestsforsomepartsofyourCodeinyourProject

Page 27: Create Unit Tests

YouarefinishedwiththeExercise

Page 28: Create Unit Tests

Poenget er ikke å luretestene,menå sørge foratkoden er feilfri!

Page 29: Create Unit Tests

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

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

Hans-PetterHalvorsen,M.Sc.

UniversityCollegeofSoutheastNorwaywww.usn.no

E-mail:[email protected]:http://home.hit.no/~hansha/