SlideShare ist ein Scribd-Unternehmen logo
1 von 28
Downloaden Sie, um offline zu lesen
L08	
  Unit	
  Testing
Reading
▪ Optional	
  
– http://www.junit.org	
  
– JUnit	
  Test	
  Infected:	
  

Programmers	
  Love	
  Writing	
  Tests
▪ Extreame	
  Programming	
  Philosophy:	
  
– “Build	
  a	
  little,	
  test	
  a	
  little”	
  
▪ All	
  classes	
  have	
  unit	
  testing	
  classes	
  
– Run	
  on	
  regular	
  basis	
  
▪ Unit	
  test	
  
– A	
  structured	
  set	
  of	
  tests	
  that	
  exercises	
  the	
  methods	
  of	
  
a	
  class	
  
▪ Test	
  Driven	
  Development	
  –	
  TDD	
  
Background
▪ Is	
  this	
  your	
  code?	
  Big	
  ball	
  of	
  Mud
Background
▪ Why	
  is	
  unit	
  testing	
  a	
  good	
  idea?	
  
▪ Reasons:	
  
– Gives	
  the	
  developer	
  confidence	
  that	
  the	
  class	
  is	
  
working	
  properly	
  
– Quickly	
  finds	
  the	
  source	
  of	
  bugs	
  
– Focuses	
  the	
  developer	
  on	
  the	
  design	
  of	
  a	
  class	
  
– Helps	
  define	
  the	
  requirements	
  of	
  the	
  individual	
  
classes
Why Unit Testing
▪ Why	
  is	
  unit	
  testing	
  a	
  good	
  idea?	
  
▪ And	
  the	
  really	
  good	
  reason:	
  
– In	
  large	
  application,	
  changes	
  and	
  re-­‐factoring	
  are	
  
possible
Why Unit Testing
1. Build	
  a	
  unit	
  test	
  to	
  test	
  a	
  class	
  during	
  design	
  
This	
  will	
  test	
  the	
  design	
  
Focuses	
  the	
  developer	
  on	
  the	
  design	
  of	
  a	
  class	
  
2. Stub	
  out	
  the	
  class	
  
All	
  tests	
  will	
  fail	
  since	
  there	
  is	
  no	
  code!	
  
3. Write	
  the	
  functionality	
  in	
  the	
  class	
  
Until	
  the	
  test	
  will	
  pass
Building the Tests
▪ An	
  open	
  source	
  Java	
  unit	
  testing	
  tool	
  
– Developed	
  by	
  Erich	
  Gamma	
  and	
  Kent	
  Beck	
  
▪ Location:	
  	
  
– www.junit.org	
  	
  
▪ JUnit	
  tests	
  does	
  not:	
  
– Take	
  the	
  place	
  of	
  functional	
  testing	
  
– Separate	
  data	
  from	
  test	
  code	
  (look	
  at	
  JUnit++)	
  
– Can’t	
  unit	
  test	
  Swing	
  GUIs,	
  JSPs	
  	
  or	
  HTML	
  (look	
  at	
  JUnit	
  
extensions)
JUnit
▪ Java	
  based	
  testing	
  framework	
  to	
  make	
  writing	
  and	
  
maintaining	
  unit	
  tests	
  easier	
  
▪ Uses	
  testcases	
  and	
  testsuits	
  to	
  build	
  a	
  	
  hierarchy	
  of	
  
tests	
  which	
  can	
  be	
  run	
  to	
  test	
  the	
  whole	
  system	
  or	
  
individual	
  modules/classes	
  
▪ The	
  developer	
  creates	
  the	
  unit	
  tests	
  using	
  JUnit	
  
utilities,	
  extends	
  JUnit	
  test	
  classes	
  and	
  uses	
  a	
  test	
  
runner	
  to	
  run	
  them
What is JUnit?
package test;
import junit.framework.TestCase;
import junit.framework.Assert;
import domain.Money;
public class MoneyTestCase extends TestCase {
private Money f12CHF;
private Money f14CHF;
protected void setUp () {
f12CHF = new Money(12, "CHF");
f14CHF = new Money(14, "CHF");
}
public void testSimpleAdd() {
Money expected = new Money(26,"CHF");
Money results = f12CHF.add(f14CHF);
Assert.assertTrue(expected.equals(results));
}
Test Case
public void testEquals ()
{
Assert.assertTrue(!f12CHF.equals(null));
Assert.assertEquals(f12CHF, f12CHF);
Assert.assertEquals(f12CHF, new Money (12, "CHF"));
Assert.assertTrue(!f12CHF.equals(f14CHF));
}
}
Test Case
@Test
public void multiplicationOfZeroIntegersShouldReturnZero() {
// MyClass is tested
MyClass tester = new MyClass();
// Tests
assertEquals("10 x 0 must be 0", 0, tester.multiply(10, 0));
assertEquals("0 x 10 must be 0", 0, tester.multiply(0, 10));
assertEquals("0 x 0 must be 0", 0, tester.multiply(0, 0));
}
Annotations
package test;
import junit.framework.TestSuite;
public class TestRunner
{
public static void main(String[] args)
{
// the testcase
String[] testCaseName = { MoneyTestCase.class.getName()};
// testrunner
junit.swingui.TestRunner.main(testCaseName);
//junit.textui.TestRunner.main(testCaseName);
}
}
Test Case Runner
junit.textui.TestRunner.main(testCaseName);
junit.swingui.TestRunner.main(testCaseName);
Running the Tests
public class TestContent extends TestCase
{
ContentServicecontentService;
protected void setUp() throws Exception
{
contentService = new ContentService();
contentService.setMailGateway(new MailServerStub());
contentService.setContentDataGateway(new ContentDataGatewayStub());
}
public void testService() throws ServiceException
{
contentService.addContent(new Content(1, "Video 1", "http", "", new D
List<Content> list = contentService.getContents();
assertEquals(list.size(), 1);
}
Example
Player Example
▪ Spring	
  Test	
  Framework	
  
▪ JUnit	
  
▪ PlayerService
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.2.1.RELEASE</version>
</dependency>
Player Example
pom.xml
package is.ru.honn.rufan.domain;



public class Player

{

protected int playerId;

protected String username;
protected String name;



public Player()

{

}



public Player(int playerId, String username, String name)

{

this.playerId = playerId;

this.username = username;

this.name = name;

}

...
Player Example
package is.ru.honn.rufan.service;



import is.ru.honn.rufan.domain.Player;



public interface PlayerService

{

public int addPlayer(Player player) throws ServiceException;

public Player getPlayer(int playerId);

}

Player Example
package is.ru.honn.rufan.service;



import is.ru.honn.rufan.domain.Player;

import java.util.ArrayList;

import java.util.List;

import java.util.logging.Logger;



public class PlayerServiceStub implements PlayerService

{

Logger log = Logger.getLogger(PlayerServiceStub.class.getName());

private List<Player> players = new ArrayList<Player>();



Player Example
public int addPlayer(Player player) throws ServiceException

{

for(Player p: players)

{

if (p.getUsername() == player.getUsername())

{

String msg = "Username: '" + player.getUsername() + 

"' already exists.";

log.info(msg);

throw new ServiceException(msg);

}

}



players.add(player);

return players.size()-1;

}



Player Example


public Player getPlayer(int playerId)

{

for(Player p: players)

{

if (p.getPlayerId() == playerId)

return p;

}



return null;

}



}

Player Example
Demo
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
beans/spring-beans.xsd">
<bean id="service"
class="is.ru.honn.rufan.service.PlayerServiceStub" />
</beans>
Player Example
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:app-test-stub.xml")
public class testPlayerService extends TestCase
{
Logger log = Logger.getLogger(testPlayerService.class.getName());
@Autowired
private PlayerService service;
@Before
public void setUp()
{
}
Player Example
@Test
public void testUser()
{
Player player0 = new Player(0, "messi", "Messi");
Player player1 = new Player(1, "ronaldo", "Ronaldo");
service.addPlayer(player0);
service.addPlayer(player1);
// Test if add works
Player playerNew = service.getPlayer(1);
assertSame(playerNew, player1);
Player Example
// Test if same username fails
try
{
service.addPlayer(player1);
}
catch (ServiceException s)
{
assertSame(ServiceException.class, s.getClass());
}
}
}
Player Example

Weitere ähnliche Inhalte

Was ist angesagt?

Implementing quality in Java projects
Implementing quality in Java projectsImplementing quality in Java projects
Implementing quality in Java projectsVincent Massol
 
TestNG Session presented in Xebia XKE
TestNG Session presented in Xebia XKETestNG Session presented in Xebia XKE
TestNG Session presented in Xebia XKEAbhishek Yadav
 
Cpp Testing Techniques Tips and Tricks - Cpp Europe
Cpp Testing Techniques Tips and Tricks - Cpp EuropeCpp Testing Techniques Tips and Tricks - Cpp Europe
Cpp Testing Techniques Tips and Tricks - Cpp EuropeClare Macrae
 
Iasi code camp 20 april 2013 implement-quality-java-massol-codecamp
Iasi code camp 20 april 2013 implement-quality-java-massol-codecampIasi code camp 20 april 2013 implement-quality-java-massol-codecamp
Iasi code camp 20 april 2013 implement-quality-java-massol-codecampCodecamp Romania
 
Quickly Testing Qt Desktop Applications
Quickly Testing Qt Desktop ApplicationsQuickly Testing Qt Desktop Applications
Quickly Testing Qt Desktop ApplicationsClare Macrae
 
IT Talk TestNG 6 vs JUnit 4
IT Talk TestNG 6 vs JUnit 4IT Talk TestNG 6 vs JUnit 4
IT Talk TestNG 6 vs JUnit 4Andrey Oleynik
 
Test Driven Development with Sql Server
Test Driven Development with Sql ServerTest Driven Development with Sql Server
Test Driven Development with Sql ServerDavid P. Moore
 
An Introduction to JUnit 5 and how to use it with Spring boot tests and Mockito
An Introduction to JUnit 5 and how to use it with Spring boot tests and MockitoAn Introduction to JUnit 5 and how to use it with Spring boot tests and Mockito
An Introduction to JUnit 5 and how to use it with Spring boot tests and Mockitoshaunthomas999
 
Unit testing with Qt test
Unit testing with Qt testUnit testing with Qt test
Unit testing with Qt testDavide Coppola
 
Apache maven, a software project management tool
Apache maven, a software project management toolApache maven, a software project management tool
Apache maven, a software project management toolRenato Primavera
 
Integration Group - Lithium test strategy
Integration Group - Lithium test strategyIntegration Group - Lithium test strategy
Integration Group - Lithium test strategyOpenDaylight
 
JUnit 5 - The Next Generation of JUnit - Ted's Tool Time
JUnit 5 - The Next Generation of JUnit - Ted's Tool TimeJUnit 5 - The Next Generation of JUnit - Ted's Tool Time
JUnit 5 - The Next Generation of JUnit - Ted's Tool TimeTed Vinke
 

Was ist angesagt? (20)

Test NG Framework Complete Walk Through
Test NG Framework Complete Walk ThroughTest NG Framework Complete Walk Through
Test NG Framework Complete Walk Through
 
TestNG with selenium
TestNG with seleniumTestNG with selenium
TestNG with selenium
 
Presentation Unit Testing process
Presentation Unit Testing processPresentation Unit Testing process
Presentation Unit Testing process
 
Implementing quality in Java projects
Implementing quality in Java projectsImplementing quality in Java projects
Implementing quality in Java projects
 
TestNG Session presented in Xebia XKE
TestNG Session presented in Xebia XKETestNG Session presented in Xebia XKE
TestNG Session presented in Xebia XKE
 
TestNG Framework
TestNG Framework TestNG Framework
TestNG Framework
 
ikp321-04
ikp321-04ikp321-04
ikp321-04
 
Cpp Testing Techniques Tips and Tricks - Cpp Europe
Cpp Testing Techniques Tips and Tricks - Cpp EuropeCpp Testing Techniques Tips and Tricks - Cpp Europe
Cpp Testing Techniques Tips and Tricks - Cpp Europe
 
Iasi code camp 20 april 2013 implement-quality-java-massol-codecamp
Iasi code camp 20 april 2013 implement-quality-java-massol-codecampIasi code camp 20 april 2013 implement-quality-java-massol-codecamp
Iasi code camp 20 april 2013 implement-quality-java-massol-codecamp
 
Quickly Testing Qt Desktop Applications
Quickly Testing Qt Desktop ApplicationsQuickly Testing Qt Desktop Applications
Quickly Testing Qt Desktop Applications
 
IT Talk TestNG 6 vs JUnit 4
IT Talk TestNG 6 vs JUnit 4IT Talk TestNG 6 vs JUnit 4
IT Talk TestNG 6 vs JUnit 4
 
Test Driven Development with Sql Server
Test Driven Development with Sql ServerTest Driven Development with Sql Server
Test Driven Development with Sql Server
 
Test ng tutorial
Test ng tutorialTest ng tutorial
Test ng tutorial
 
An Introduction to JUnit 5 and how to use it with Spring boot tests and Mockito
An Introduction to JUnit 5 and how to use it with Spring boot tests and MockitoAn Introduction to JUnit 5 and how to use it with Spring boot tests and Mockito
An Introduction to JUnit 5 and how to use it with Spring boot tests and Mockito
 
Php unit (eng)
Php unit (eng)Php unit (eng)
Php unit (eng)
 
Unit testing in Unity
Unit testing in UnityUnit testing in Unity
Unit testing in Unity
 
Unit testing with Qt test
Unit testing with Qt testUnit testing with Qt test
Unit testing with Qt test
 
Apache maven, a software project management tool
Apache maven, a software project management toolApache maven, a software project management tool
Apache maven, a software project management tool
 
Integration Group - Lithium test strategy
Integration Group - Lithium test strategyIntegration Group - Lithium test strategy
Integration Group - Lithium test strategy
 
JUnit 5 - The Next Generation of JUnit - Ted's Tool Time
JUnit 5 - The Next Generation of JUnit - Ted's Tool TimeJUnit 5 - The Next Generation of JUnit - Ted's Tool Time
JUnit 5 - The Next Generation of JUnit - Ted's Tool Time
 

Andere mochten auch (14)

L09 Process Design
L09 Process DesignL09 Process Design
L09 Process Design
 
L07 Frameworks
L07 FrameworksL07 Frameworks
L07 Frameworks
 
L22 Design Principles
L22 Design PrinciplesL22 Design Principles
L22 Design Principles
 
L11 Service Design and REST
L11 Service Design and RESTL11 Service Design and REST
L11 Service Design and REST
 
L12 Visualizing Architecture
L12 Visualizing ArchitectureL12 Visualizing Architecture
L12 Visualizing Architecture
 
L16 Documenting Software
L16 Documenting SoftwareL16 Documenting Software
L16 Documenting Software
 
L17 Data Source Layer
L17 Data Source LayerL17 Data Source Layer
L17 Data Source Layer
 
L15 Organising Domain Layer
L15 Organising Domain LayerL15 Organising Domain Layer
L15 Organising Domain Layer
 
L18 Object Relational Mapping
L18 Object Relational MappingL18 Object Relational Mapping
L18 Object Relational Mapping
 
L10 Architecture Considerations
L10 Architecture ConsiderationsL10 Architecture Considerations
L10 Architecture Considerations
 
L21 Architecture and Agile
L21 Architecture and AgileL21 Architecture and Agile
L21 Architecture and Agile
 
L20 Scalability
L20 ScalabilityL20 Scalability
L20 Scalability
 
L19 Application Architecture
L19 Application ArchitectureL19 Application Architecture
L19 Application Architecture
 
Commercial track 2_UDP Solution Selling Made Simple
Commercial track 2_UDP Solution Selling Made SimpleCommercial track 2_UDP Solution Selling Made Simple
Commercial track 2_UDP Solution Selling Made Simple
 

Ähnlich wie L08 Unit Testing

Testing And Drupal
Testing And DrupalTesting And Drupal
Testing And DrupalPeter Arato
 
Unit testing php-unit - phing - selenium_v2
Unit testing   php-unit - phing - selenium_v2Unit testing   php-unit - phing - selenium_v2
Unit testing php-unit - phing - selenium_v2Tricode (part of Dept)
 
Testing basics for developers
Testing basics for developersTesting basics for developers
Testing basics for developersAnton Udovychenko
 
Maven and j unit introduction
Maven and j unit introductionMaven and j unit introduction
Maven and j unit introductionSergii Fesenko
 
Google test training
Google test trainingGoogle test training
Google test trainingThierry Gayet
 
Junit and cactus
Junit and cactusJunit and cactus
Junit and cactusHimanshu
 
Testes? Mas isso não aumenta o tempo de projecto? Não quero...
Testes? Mas isso não aumenta o tempo de projecto? Não quero...Testes? Mas isso não aumenta o tempo de projecto? Não quero...
Testes? Mas isso não aumenta o tempo de projecto? Não quero...Comunidade NetPonto
 
Unit Testing in .NET Core 7.0 with XUnit.pptx
Unit Testing in .NET Core 7.0 with XUnit.pptxUnit Testing in .NET Core 7.0 with XUnit.pptx
Unit Testing in .NET Core 7.0 with XUnit.pptxKnoldus Inc.
 
An introduction to unit testing
An introduction to unit testingAn introduction to unit testing
An introduction to unit testingAdam Stephensen
 
J unit presentation
J unit presentationJ unit presentation
J unit presentationPriya Sharma
 
Testing with JUnit 5 and Spring
Testing with JUnit 5 and SpringTesting with JUnit 5 and Spring
Testing with JUnit 5 and SpringVMware Tanzu
 
Beginners - Get Started With Unit Testing in .NET
Beginners - Get Started With Unit Testing in .NETBeginners - Get Started With Unit Testing in .NET
Beginners - Get Started With Unit Testing in .NETBaskar K
 
Java 201 Intro to Test Driven Development in Java
Java 201   Intro to Test Driven Development in JavaJava 201   Intro to Test Driven Development in Java
Java 201 Intro to Test Driven Development in Javaagorolabs
 

Ähnlich wie L08 Unit Testing (20)

Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Testing And Drupal
Testing And DrupalTesting And Drupal
Testing And Drupal
 
Unit testing php-unit - phing - selenium_v2
Unit testing   php-unit - phing - selenium_v2Unit testing   php-unit - phing - selenium_v2
Unit testing php-unit - phing - selenium_v2
 
Testing basics for developers
Testing basics for developersTesting basics for developers
Testing basics for developers
 
Maven and j unit introduction
Maven and j unit introductionMaven and j unit introduction
Maven and j unit introduction
 
Google test training
Google test trainingGoogle test training
Google test training
 
Junit and cactus
Junit and cactusJunit and cactus
Junit and cactus
 
Junit and testNG
Junit and testNGJunit and testNG
Junit and testNG
 
Testes? Mas isso não aumenta o tempo de projecto? Não quero...
Testes? Mas isso não aumenta o tempo de projecto? Não quero...Testes? Mas isso não aumenta o tempo de projecto? Não quero...
Testes? Mas isso não aumenta o tempo de projecto? Não quero...
 
Qunit testing slider
Qunit testing sliderQunit testing slider
Qunit testing slider
 
JUnit 5
JUnit 5JUnit 5
JUnit 5
 
Unit Testing in .NET Core 7.0 with XUnit.pptx
Unit Testing in .NET Core 7.0 with XUnit.pptxUnit Testing in .NET Core 7.0 with XUnit.pptx
Unit Testing in .NET Core 7.0 with XUnit.pptx
 
An introduction to unit testing
An introduction to unit testingAn introduction to unit testing
An introduction to unit testing
 
J unit presentation
J unit presentationJ unit presentation
J unit presentation
 
JUnit Presentation
JUnit PresentationJUnit Presentation
JUnit Presentation
 
Testing with JUnit 5 and Spring
Testing with JUnit 5 and SpringTesting with JUnit 5 and Spring
Testing with JUnit 5 and Spring
 
8-testing.pptx
8-testing.pptx8-testing.pptx
8-testing.pptx
 
Beginners - Get Started With Unit Testing in .NET
Beginners - Get Started With Unit Testing in .NETBeginners - Get Started With Unit Testing in .NET
Beginners - Get Started With Unit Testing in .NET
 
Junit_.pptx
Junit_.pptxJunit_.pptx
Junit_.pptx
 
Java 201 Intro to Test Driven Development in Java
Java 201   Intro to Test Driven Development in JavaJava 201   Intro to Test Driven Development in Java
Java 201 Intro to Test Driven Development in Java
 

Mehr von Ólafur Andri Ragnarsson

New Technology Summer 2020 Course Introduction
New Technology Summer 2020 Course IntroductionNew Technology Summer 2020 Course Introduction
New Technology Summer 2020 Course IntroductionÓlafur Andri Ragnarsson
 
New Technology 2019 L13 Rise of the Machine
New Technology 2019 L13 Rise of the Machine New Technology 2019 L13 Rise of the Machine
New Technology 2019 L13 Rise of the Machine Ólafur Andri Ragnarsson
 

Mehr von Ólafur Andri Ragnarsson (20)

Nýsköpun - Leiðin til framfara
Nýsköpun - Leiðin til framfaraNýsköpun - Leiðin til framfara
Nýsköpun - Leiðin til framfara
 
Nýjast tækni og framtíðin
Nýjast tækni og framtíðinNýjast tækni og framtíðin
Nýjast tækni og framtíðin
 
New Technology Summer 2020 Course Introduction
New Technology Summer 2020 Course IntroductionNew Technology Summer 2020 Course Introduction
New Technology Summer 2020 Course Introduction
 
L01 Introduction
L01 IntroductionL01 Introduction
L01 Introduction
 
L23 Robotics and Drones
L23 Robotics and Drones L23 Robotics and Drones
L23 Robotics and Drones
 
L22 Augmented and Virtual Reality
L22 Augmented and Virtual RealityL22 Augmented and Virtual Reality
L22 Augmented and Virtual Reality
 
L20 Personalised World
L20 Personalised WorldL20 Personalised World
L20 Personalised World
 
L19 Network Platforms
L19 Network PlatformsL19 Network Platforms
L19 Network Platforms
 
L18 Big Data and Analytics
L18 Big Data and AnalyticsL18 Big Data and Analytics
L18 Big Data and Analytics
 
L17 Algorithms and AI
L17 Algorithms and AIL17 Algorithms and AI
L17 Algorithms and AI
 
L16 Internet of Things
L16 Internet of ThingsL16 Internet of Things
L16 Internet of Things
 
L14 From the Internet to Blockchain
L14 From the Internet to BlockchainL14 From the Internet to Blockchain
L14 From the Internet to Blockchain
 
L14 The Mobile Revolution
L14 The Mobile RevolutionL14 The Mobile Revolution
L14 The Mobile Revolution
 
New Technology 2019 L13 Rise of the Machine
New Technology 2019 L13 Rise of the Machine New Technology 2019 L13 Rise of the Machine
New Technology 2019 L13 Rise of the Machine
 
L12 digital transformation
L12 digital transformationL12 digital transformation
L12 digital transformation
 
L10 The Innovator's Dilemma
L10 The Innovator's DilemmaL10 The Innovator's Dilemma
L10 The Innovator's Dilemma
 
L09 Disruptive Technology
L09 Disruptive TechnologyL09 Disruptive Technology
L09 Disruptive Technology
 
L09 Technological Revolutions
L09 Technological RevolutionsL09 Technological Revolutions
L09 Technological Revolutions
 
L07 Becoming Invisible
L07 Becoming InvisibleL07 Becoming Invisible
L07 Becoming Invisible
 
L06 Diffusion of Innovation
L06 Diffusion of InnovationL06 Diffusion of Innovation
L06 Diffusion of Innovation
 

Kürzlich hochgeladen

The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceanilsa9823
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 

Kürzlich hochgeladen (20)

The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 

L08 Unit Testing

  • 2. Reading ▪ Optional   – http://www.junit.org   – JUnit  Test  Infected:  
 Programmers  Love  Writing  Tests
  • 3. ▪ Extreame  Programming  Philosophy:   – “Build  a  little,  test  a  little”   ▪ All  classes  have  unit  testing  classes   – Run  on  regular  basis   ▪ Unit  test   – A  structured  set  of  tests  that  exercises  the  methods  of   a  class   ▪ Test  Driven  Development  –  TDD   Background
  • 4. ▪ Is  this  your  code?  Big  ball  of  Mud Background
  • 5. ▪ Why  is  unit  testing  a  good  idea?   ▪ Reasons:   – Gives  the  developer  confidence  that  the  class  is   working  properly   – Quickly  finds  the  source  of  bugs   – Focuses  the  developer  on  the  design  of  a  class   – Helps  define  the  requirements  of  the  individual   classes Why Unit Testing
  • 6. ▪ Why  is  unit  testing  a  good  idea?   ▪ And  the  really  good  reason:   – In  large  application,  changes  and  re-­‐factoring  are   possible Why Unit Testing
  • 7. 1. Build  a  unit  test  to  test  a  class  during  design   This  will  test  the  design   Focuses  the  developer  on  the  design  of  a  class   2. Stub  out  the  class   All  tests  will  fail  since  there  is  no  code!   3. Write  the  functionality  in  the  class   Until  the  test  will  pass Building the Tests
  • 8. ▪ An  open  source  Java  unit  testing  tool   – Developed  by  Erich  Gamma  and  Kent  Beck   ▪ Location:     – www.junit.org     ▪ JUnit  tests  does  not:   – Take  the  place  of  functional  testing   – Separate  data  from  test  code  (look  at  JUnit++)   – Can’t  unit  test  Swing  GUIs,  JSPs    or  HTML  (look  at  JUnit   extensions) JUnit
  • 9. ▪ Java  based  testing  framework  to  make  writing  and   maintaining  unit  tests  easier   ▪ Uses  testcases  and  testsuits  to  build  a    hierarchy  of   tests  which  can  be  run  to  test  the  whole  system  or   individual  modules/classes   ▪ The  developer  creates  the  unit  tests  using  JUnit   utilities,  extends  JUnit  test  classes  and  uses  a  test   runner  to  run  them What is JUnit?
  • 10. package test; import junit.framework.TestCase; import junit.framework.Assert; import domain.Money; public class MoneyTestCase extends TestCase { private Money f12CHF; private Money f14CHF; protected void setUp () { f12CHF = new Money(12, "CHF"); f14CHF = new Money(14, "CHF"); } public void testSimpleAdd() { Money expected = new Money(26,"CHF"); Money results = f12CHF.add(f14CHF); Assert.assertTrue(expected.equals(results)); } Test Case
  • 11. public void testEquals () { Assert.assertTrue(!f12CHF.equals(null)); Assert.assertEquals(f12CHF, f12CHF); Assert.assertEquals(f12CHF, new Money (12, "CHF")); Assert.assertTrue(!f12CHF.equals(f14CHF)); } } Test Case
  • 12.
  • 13. @Test public void multiplicationOfZeroIntegersShouldReturnZero() { // MyClass is tested MyClass tester = new MyClass(); // Tests assertEquals("10 x 0 must be 0", 0, tester.multiply(10, 0)); assertEquals("0 x 10 must be 0", 0, tester.multiply(0, 10)); assertEquals("0 x 0 must be 0", 0, tester.multiply(0, 0)); } Annotations
  • 14. package test; import junit.framework.TestSuite; public class TestRunner { public static void main(String[] args) { // the testcase String[] testCaseName = { MoneyTestCase.class.getName()}; // testrunner junit.swingui.TestRunner.main(testCaseName); //junit.textui.TestRunner.main(testCaseName); } } Test Case Runner
  • 16. public class TestContent extends TestCase { ContentServicecontentService; protected void setUp() throws Exception { contentService = new ContentService(); contentService.setMailGateway(new MailServerStub()); contentService.setContentDataGateway(new ContentDataGatewayStub()); } public void testService() throws ServiceException { contentService.addContent(new Content(1, "Video 1", "http", "", new D List<Content> list = contentService.getContents(); assertEquals(list.size(), 1); } Example
  • 17. Player Example ▪ Spring  Test  Framework   ▪ JUnit   ▪ PlayerService
  • 19. package is.ru.honn.rufan.domain;
 
 public class Player
 {
 protected int playerId;
 protected String username; protected String name;
 
 public Player()
 {
 }
 
 public Player(int playerId, String username, String name)
 {
 this.playerId = playerId;
 this.username = username;
 this.name = name;
 }
 ... Player Example
  • 20. package is.ru.honn.rufan.service;
 
 import is.ru.honn.rufan.domain.Player;
 
 public interface PlayerService
 {
 public int addPlayer(Player player) throws ServiceException;
 public Player getPlayer(int playerId);
 }
 Player Example
  • 21. package is.ru.honn.rufan.service;
 
 import is.ru.honn.rufan.domain.Player;
 import java.util.ArrayList;
 import java.util.List;
 import java.util.logging.Logger;
 
 public class PlayerServiceStub implements PlayerService
 {
 Logger log = Logger.getLogger(PlayerServiceStub.class.getName());
 private List<Player> players = new ArrayList<Player>();
 
 Player Example
  • 22. public int addPlayer(Player player) throws ServiceException
 {
 for(Player p: players)
 {
 if (p.getUsername() == player.getUsername())
 {
 String msg = "Username: '" + player.getUsername() + 
 "' already exists.";
 log.info(msg);
 throw new ServiceException(msg);
 }
 }
 
 players.add(player);
 return players.size()-1;
 }
 
 Player Example
  • 23. 
 public Player getPlayer(int playerId)
 {
 for(Player p: players)
 {
 if (p.getPlayerId() == playerId)
 return p;
 }
 
 return null;
 }
 
 }
 Player Example
  • 24. Demo
  • 25. <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans beans/spring-beans.xsd"> <bean id="service" class="is.ru.honn.rufan.service.PlayerServiceStub" /> </beans> Player Example
  • 26. @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:app-test-stub.xml") public class testPlayerService extends TestCase { Logger log = Logger.getLogger(testPlayerService.class.getName()); @Autowired private PlayerService service; @Before public void setUp() { } Player Example
  • 27. @Test public void testUser() { Player player0 = new Player(0, "messi", "Messi"); Player player1 = new Player(1, "ronaldo", "Ronaldo"); service.addPlayer(player0); service.addPlayer(player1); // Test if add works Player playerNew = service.getPlayer(1); assertSame(playerNew, player1); Player Example
  • 28. // Test if same username fails try { service.addPlayer(player1); } catch (ServiceException s) { assertSame(ServiceException.class, s.getClass()); } } } Player Example