SlideShare uma empresa Scribd logo
1 de 41
Unit Testing
30/04/2014 - Giacomo Petronio
Cronoprogramma
● Software testing e software checking
● Livelli di test
● Unit test / JUnit
● Codice testabile
● Dependency Inversion
● Friendly Classes
● Test-Driven Development
Software Testing
Venire a
conoscenza di
eventuali rischi
Verifica dei requisiti
espliciti ed impliciti
Valutazione della
Qualità
● Correttezza
● Affidabilità
● Robustezza
● Usabilità
● Efficienza
● Manutenibilità
● Portabilità
Software Checking
Attività che mira a valutare un attributo o un
comportamento di un sistema, ed a verificare
che questo soddisfi i requisiti.
Checking is the process of making evaluations by applying
algorithmic decision rules to specific observations of a product.
Test Correttezza
Black-box
Basati sulle specifiche
Diversi livelli
Test Correttezza
Livello Pro Contro
System
tests
alta confidenza se tutto OK lenti
poco indicativi in caso di fail
difficilmente automatizzabili
Unit tests veloci
molto indicativi in caso di fail
automatizzabili
confidenza relativa
# tests
tempo
esecuzione
Scenario
Integration Tests
Unit Tests
test intero sistema
punto di vista dell'utente
test di collezioni di classi
sottosistemi isolati
test di classi singole
Livelli di test
Struttura Unit Test
Test Driver
Unit Under
Test
Stimolo
Assert
Contesto
JUnit
JUnit Asserts
assertEquals(expected, actual)
assertTrue(value)
assertFalse(value)
assertNull(value)
assertNotNull(value)
assertThat(value, Matcher)
● assertThat(value, is("A"));
● assertThat(value, is(true));
● assertThat(value, is(notNull()));
Running JUnit Tests
JUnit Best Practices
● N model classes → N test classes
● 1 test case per funzionalità
Stack Test Cases
● test Empty Stack
● test Correct Order
● test Null Input
● test Pop When Empty
JUnit Best Practices
Un assert per test
case
Stack stack = new Stack();
stack.push("A");
assertFalse(stack.isEmpty());
assertEquals("A", stack.peek());
assertFalse(stack.isEmpty());
assertEquals("A", stack.pop());
assertTrue(stack.isEmpty());
JUnit Best Practices
White box / Black box
JUnit Best Practices
Come testo un metodo privato?
● non testare
● reflection
● cambiare visibilità
● classe emergente
JUnit Best Practices
Nome Classe di Test
Stack StackTest
Stesso package ma diversa cartella
● src/it/units/inginf
o Stack.java
● test/it/units/inginf
o StackTest.java
stackShouldBeEmpty(){ … }
popShouldReturnNullWhenEmpty(){ … }
peekShouldNotRemoveItem(){ … }
JUnit Best Practices
Nomi test-case verbosi
test01(){ … }
test02(){ … }
JUnit Best Practices
Testare le eccezioni
@Test(expected=NullPointerException.class)
public void shouldThrowExceptionOnNullInput() {
Stack stack = new Stack();
stack.push(null);
}
JUnit Best Practices
Classi di equivalenza
Testare tutti gli input Risorse Limitate
VS
IMPORTANTE!!
Caratteristiche di ogni Unit Test
Velocità Ripetibilità Indipendenza
DBMS
Networking
File-System
Benefici Unit Testing
1
2 3
Documentazion
e
Regression testing
Refactoring
Facile…
Test
Driver
Unit Under
Test
Stimolo
Assert
Contesto
… o no?
Come scrivere codice non testabile
● Mescolare i new con la logica
● Codice nel costruttore
● Global state (es. singletons)
● Metodi statici
● Troppi condizionali
● Troppe responsabilità
Test
Driver
Unit Under
Test
Stimolo
Assert
Contesto
Other
Class
Other
Class
Other
Class
DB
File
System
Internet
Facile…?
Test
Driver
Unit Under
Test
Stimolo
Assert
Contesto
Other
Class
Other
Class
Other
Class
DB
File
System
Internet
Codice Testabile
SEAM
Test
Driver
Unit Under
Test
Stimolo
Assert
Contesto
Friendly
Friendly
Friendly
Codice Testabile
SEAM
Codice Testabile
Crezione
Business Logic
Grafo degli Oggetti
Test
Driver
Unit Under
Test
Friendly
Friendly
Friendly
Codice Testabile
SEAM
Oggetto istanziato
Dependency Inversion SOLID
Concrete, Abstract
Concrete Abstract
class Geek {
playWith(PlayStation ps){
ps.play();
}
}
class Geek {
playWith(IConsolle c){
c.play();
}
}
Esempio
MovieFilter
+moviesDirectedBy(director)
<<Interface>>
MovieFinder
+ getAllMovies()
MovieFinderImpl<<crea>>
esempio…
Inversion of Control (IoC)
MovieFilter
+moviesDirectedBy(director)
<<Interface>>
MovieFinder
+ getAllMovies()
MovieFinderImpl<<crea>>
Assemblatore <<crea>>
<<inject>>
IoC: Dependency Injection
● Constructor Injection
o Dipendenze esplicite
● Setter Injection
o Dipendenze meno esplicite
o Comodo in classi esistenti
● Framework
o Guice
o Spring
o CDI (J2EE)
IoC: Service Locator
MovieFilter
+moviesDirectedBy(director)
<<Interface>>
MovieFinder
+ getAllMovies()
MovieFinderImpl
Service Locator
<<chiede>>
<<crea>>
Friendly Classes
Stub
● Non hanno logica interna
● Comportamento predefinito
● Non si effettuano verifiche sugli stub
● Es. finta risorsa web
Friendly Classes
Mock
Programmabile:
● “Quando ricevi X…”
o restituisci Y
o lancia eccezione
o …
Verifiche sui mock:
● Numero di chiamate
● Controllo parametro passato
Mockito
Mock Lifecycle:
● Crea mock a partire da interfaccia
● Programma comportamento voluto
● Utilizzo indiretto
● Verifica dell’utilizzo
Mockito
Esempio
MovieFinder finder = mock(MovieFinder.class)
when(finder.findAll()).thenReturn(allMovies);
MovieFilter filter = new MovieFilter(finder);
Lister.moviesDirectedBy(“Martin Scorsese”);
verify(finder).findAll(); // verifica la chiamata
esempio…
Mockito
MovieFinder finder = mock(MovieFinder.class)
when(finder.findAll()).___________
.thenReturn(allMovies);
.thenReturn(none, all);
.thenThrows(new RuntimeException());
.then( callback );
MovieLister lister = mock(MovieLister.class)
when(lister.moviesDirectedBy(_____)).then(…);
“Martin Scorsese”
anyString()
any()
Legacy Code
“Codice ereditato da altri?”
“Codice rimasto da una versione precedente?”
Codice senza test
Test Driven Development
Si sviluppa in 3 fasi:
RED scrivere un singolo test che fallisce
GREEN scrivere quanto basta per far passare i test
BLUE refactoring
Metodologia di
sviluppo
Test Driven Development
Test First
Effetti diretti sul codice:
● Disaccoppiato
● Coeso
● Testabile
● API Driven

Mais conteúdo relacionado

Semelhante a Unit testing 2014

Software Testing & Test Driven Development
Software Testing & Test Driven DevelopmentSoftware Testing & Test Driven Development
Software Testing & Test Driven DevelopmentSergio Santoro
 
Qualità del Software
Qualità del SoftwareQualità del Software
Qualità del SoftwareYeser Rema
 
Java Unit Testing - Introduction
Java Unit Testing - IntroductionJava Unit Testing - Introduction
Java Unit Testing - Introductionfgianneschi
 
PowerMock TDD User Group Milano
PowerMock TDD User Group MilanoPowerMock TDD User Group Milano
PowerMock TDD User Group MilanoMassimo Groppelli
 
Webinar: “Testing automatico: la scelta vincente per ottenere una riduzione d...
Webinar: “Testing automatico: la scelta vincente per ottenere una riduzione d...Webinar: “Testing automatico: la scelta vincente per ottenere una riduzione d...
Webinar: “Testing automatico: la scelta vincente per ottenere una riduzione d...Emerasoft, solutions to collaborate
 
L'Occhio di Ra sul Testing
L'Occhio di Ra sul TestingL'Occhio di Ra sul Testing
L'Occhio di Ra sul TestingFelice Pescatore
 
Unit testing in Visual Studio 2013
Unit testing in Visual Studio 2013Unit testing in Visual Studio 2013
Unit testing in Visual Studio 2013DomusDotNet
 
Introduzione al Testing
Introduzione al TestingIntroduzione al Testing
Introduzione al TestingDotNetMarche
 
05 sicurezza delle applicazioni per le aziende nel settore della pubblica uti...
05 sicurezza delle applicazioni per le aziende nel settore della pubblica uti...05 sicurezza delle applicazioni per le aziende nel settore della pubblica uti...
05 sicurezza delle applicazioni per le aziende nel settore della pubblica uti...IBM Italia Web Team
 
Android Test Driven Development
Android Test Driven DevelopmentAndroid Test Driven Development
Android Test Driven Developmentsazilla
 
Fe05 test drivenjavascriptdevelopment
Fe05   test drivenjavascriptdevelopmentFe05   test drivenjavascriptdevelopment
Fe05 test drivenjavascriptdevelopmentDotNetCampus
 
CONTINUOUS INTEGRATION CON SQL SERVER
CONTINUOUS INTEGRATION CON SQL SERVERCONTINUOUS INTEGRATION CON SQL SERVER
CONTINUOUS INTEGRATION CON SQL SERVERDotNetCampus
 
DotNetCampus - Continuous Integration con Sql Server
DotNetCampus - Continuous Integration con Sql ServerDotNetCampus - Continuous Integration con Sql Server
DotNetCampus - Continuous Integration con Sql ServerAlessandro Alpi
 
Introduzione al Test Driven Development
Introduzione al Test Driven DevelopmentIntroduzione al Test Driven Development
Introduzione al Test Driven DevelopmentEnnio Masi
 
TPi: una metodologia per il miglioramento del processo di test, by Andrea Di ...
TPi: una metodologia per il miglioramento del processo di test, by Andrea Di ...TPi: una metodologia per il miglioramento del processo di test, by Andrea Di ...
TPi: una metodologia per il miglioramento del processo di test, by Andrea Di ...Codemotion
 
Extended Summary of "Search-Based SQL Injection Attacks Testing using Genetic...
Extended Summary of "Search-Based SQL Injection Attacks Testing using Genetic...Extended Summary of "Search-Based SQL Injection Attacks Testing using Genetic...
Extended Summary of "Search-Based SQL Injection Attacks Testing using Genetic...AndreaGonzato
 
Benchmarking - Architettura degli Elaboratori - AA 2010/2011 - UNICAM
Benchmarking - Architettura degli Elaboratori - AA 2010/2011 - UNICAMBenchmarking - Architettura degli Elaboratori - AA 2010/2011 - UNICAM
Benchmarking - Architettura degli Elaboratori - AA 2010/2011 - UNICAMNicola Paoletti
 

Semelhante a Unit testing 2014 (20)

Software Testing & Test Driven Development
Software Testing & Test Driven DevelopmentSoftware Testing & Test Driven Development
Software Testing & Test Driven Development
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
Qualità del Software
Qualità del SoftwareQualità del Software
Qualità del Software
 
Unit test
Unit testUnit test
Unit test
 
Unit testing 101
Unit testing 101Unit testing 101
Unit testing 101
 
Java Unit Testing - Introduction
Java Unit Testing - IntroductionJava Unit Testing - Introduction
Java Unit Testing - Introduction
 
PowerMock TDD User Group Milano
PowerMock TDD User Group MilanoPowerMock TDD User Group Milano
PowerMock TDD User Group Milano
 
Webinar: “Testing automatico: la scelta vincente per ottenere una riduzione d...
Webinar: “Testing automatico: la scelta vincente per ottenere una riduzione d...Webinar: “Testing automatico: la scelta vincente per ottenere una riduzione d...
Webinar: “Testing automatico: la scelta vincente per ottenere una riduzione d...
 
L'Occhio di Ra sul Testing
L'Occhio di Ra sul TestingL'Occhio di Ra sul Testing
L'Occhio di Ra sul Testing
 
Unit testing in Visual Studio 2013
Unit testing in Visual Studio 2013Unit testing in Visual Studio 2013
Unit testing in Visual Studio 2013
 
Introduzione al Testing
Introduzione al TestingIntroduzione al Testing
Introduzione al Testing
 
05 sicurezza delle applicazioni per le aziende nel settore della pubblica uti...
05 sicurezza delle applicazioni per le aziende nel settore della pubblica uti...05 sicurezza delle applicazioni per le aziende nel settore della pubblica uti...
05 sicurezza delle applicazioni per le aziende nel settore della pubblica uti...
 
Android Test Driven Development
Android Test Driven DevelopmentAndroid Test Driven Development
Android Test Driven Development
 
Fe05 test drivenjavascriptdevelopment
Fe05   test drivenjavascriptdevelopmentFe05   test drivenjavascriptdevelopment
Fe05 test drivenjavascriptdevelopment
 
CONTINUOUS INTEGRATION CON SQL SERVER
CONTINUOUS INTEGRATION CON SQL SERVERCONTINUOUS INTEGRATION CON SQL SERVER
CONTINUOUS INTEGRATION CON SQL SERVER
 
DotNetCampus - Continuous Integration con Sql Server
DotNetCampus - Continuous Integration con Sql ServerDotNetCampus - Continuous Integration con Sql Server
DotNetCampus - Continuous Integration con Sql Server
 
Introduzione al Test Driven Development
Introduzione al Test Driven DevelopmentIntroduzione al Test Driven Development
Introduzione al Test Driven Development
 
TPi: una metodologia per il miglioramento del processo di test, by Andrea Di ...
TPi: una metodologia per il miglioramento del processo di test, by Andrea Di ...TPi: una metodologia per il miglioramento del processo di test, by Andrea Di ...
TPi: una metodologia per il miglioramento del processo di test, by Andrea Di ...
 
Extended Summary of "Search-Based SQL Injection Attacks Testing using Genetic...
Extended Summary of "Search-Based SQL Injection Attacks Testing using Genetic...Extended Summary of "Search-Based SQL Injection Attacks Testing using Genetic...
Extended Summary of "Search-Based SQL Injection Attacks Testing using Genetic...
 
Benchmarking - Architettura degli Elaboratori - AA 2010/2011 - UNICAM
Benchmarking - Architettura degli Elaboratori - AA 2010/2011 - UNICAMBenchmarking - Architettura degli Elaboratori - AA 2010/2011 - UNICAM
Benchmarking - Architettura degli Elaboratori - AA 2010/2011 - UNICAM
 

Unit testing 2014