SlideShare a Scribd company logo
SOMMARIOSOMMARIO
Test automatici e TDD
Installazione e utilizzo di googletest
Test con googlemock
Risolviamo un code kata
Domande
YURI VALENTINIYURI VALENTINI
SW Windows e Linux
FW schede embedded
Linguaggi: C/C++, C#, Python
Ambiti:
Videoconferenza e VOIP
Automazione industriale
Biomedicale
yuroller@gmail.com
https://github.com/yuroller
TESTING VS CHECKINGTESTING VS CHECKING
Richiede persona
senziente
Automatizzabile
Fa scoprire nuove cose Conferma le nostre
assunzioni
Fa richieste inedite Fa sempre le stesse
richieste
Esplorazione e scoperta
di nuove cose
Assicura che il
programma funzioni
Michael Bolton blog post
INSTALLAZIONEINSTALLAZIONE VCPKGVCPKG
> git clone https://github.com/Microsoft/vcpkg.git
> cd vcpkg
> bootstrap-vcpkg.bat
(admin)> vcpkg integrate install
> vcpkg install gtest:x64-windows
VISUAL STUDIOVISUAL STUDIO
Creare una solution
Creare il progetto di test (console)
Aggiungere:
Definire:
Linker → Debugging: /DEBUG:FULL
Rimuovere: main()
gtest{d}.lib;gtest_main{d}.lib
_SILENCE_TR1_NAMESPACE_DEPRECATION_WARNI
PRIMO TESTPRIMO TEST
#include <gtest/gtest.h>
TEST(TrivialTest, ChecksWeCanTest) {
EXPECT_EQ(0, 1);
}
LINUXLINUX
Installare strumenti sviluppo e cmake
Ottenere sorgenti gtest
Makefile:
$ mkdir build
$ cd build
$ cmake ..
$ make && make install
TestApp: TestApp.cpp
g++ -g -Wall -o TestApp TestApp.cpp 
-I../install/include -L../install/lib 
-lgtest -lgtest_main -lpthread
.PHONY: clean
clean:
rm TestApp
GTEST_MAIN.CCGTEST_MAIN.CC
#include <stdio.h>
#include "gtest/gtest.h"
GTEST_API_ int main(int argc, char **argv) {
printf("Running main() from gtest_main.ccn");
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
ESEGUIRE I TESTESEGUIRE I TEST
Linea di comando
Test runner esterno
Visual Studio Test Explorer
ASSERZIONIASSERZIONI
ASSERT_*, EXPECT_*
TRUE, FALSE
EQ, NE, LT, LE, GT, GE
C-strings: STREQ, STRNE
Immediato: FAIL(), SUCCEED()
Eccezioni: THROW, ANY_THROW, NO_THROW
FLOAT_EQ, DOUBLE_EQ, NEAR
Windows: HRESULT_SUCCEEDED, HRESULT_FAILED
Documentazione gtest
ASSERZIONI GMOCKASSERZIONI GMOCK
ASSERT_THAT, EXPECT_THAT
Generici: Eq, Ge, IsNull, NotNull
FP: FloatEq, DoubleEq, FloatNear, DoubleNear
String: MatchesRegex, StartsWith, HasSubstr
stl: Eq, Contains, IsEmpty, SizeIs
std::pair → Pair - std::map → Key
Documentazione gmock
TEST FIXTURETEST FIXTURE
class BarTest : public ::testing::Test {
protected:
BarTest() {
instance_resource_ = new ...;
// inizialization
}
~BarTest() { delete instance_resource_; }
// virtual void SetUp()
// virtual void TearDown()
T* instance_resource_; // reacreated each test
};
TEST_F(BarTest, Test0) { ... }
RISORSA CONDIVISARISORSA CONDIVISA
class FooTest : public ::testing::Test {
protected:
static void SetUpTestCase() {
shared_resource_ = new ...;
}
static void TearDownTestCase() {
delete shared_resource_;
shared_resource_ = nullptr;
}
static T* shared_resource_; // Shared expensive resource
};
T* FooTest::shared_resource_ = nullptr;
TEST_F(FooTest, Test1) { ... }
VARIEVARIE
DISABLED_
death test
global fixtures
test parametrici (TEST_P)
esecuzione parallela
esecuzione ordine casuale
filtri per esecuzione test
FIRSTFIRST
Fast
Isolated/Independent
Repeatable
Self-Validating
Thorough and Timely
MODELLO 3A PER TESTMODELLO 3A PER TEST
Arrange
Act
Assert
NOMI DEI TESTNOMI DEI TEST
Ognuno ha la sua convenzione
Test Case: {nome_classe/scenario}Test
Test Name: {descrizione_del_test}
Alcuni usano: MethodName_GivenConditions
_WhenThisHappens_ThenThisisExpectedResult
TEST(FactorialTest, HandlesZeroInput)
sumOfTwoNumbers_givenTwoPositiveNumbers
_WhenNumbersArePositive_ThenResultIsPositive()
COSA TESTARECOSA TESTARE
Coverage del codice sorgente
Condizioni dell'if
Input valido e input NON valido
exception
TDDTDD
"TDD by Example" ‐ Kent Beck
1. Quickly add a test
2. Run all tests and see the new one fail
3. Make a little change
4. Run all tests and see them all
succeed
5. Refactor to remove duplication
REFACTORINGREFACTORING
Rimuovi la duplicazione (DRY)
Usa nomi appropriati
Semplifica le classi/funzioni (SRP)
STILE DI TESTSTILE DI TEST
Classicista (Chicago/Detroit school)
Mockista (London school) GOOS
Fake
Stub
Mock
TEST DOUBLESTEST DOUBLES
FAKEFAKE
Fakes are objects that have working
implementations, but not same as
production one. Usually they take some
shortcut and have simplified version of
production code.
STUBSTUB
Stub is an object that holds predefined
data and uses it to answer calls during
tests. It is used when we cannot or
don’t want to involve objects that
would answer with real data or have
undesirable side effects.
MOCKMOCK
Mocks are objects that register calls
they receive. In test assertion we can
verify on Mocks that all expected
actions were performed.
A COSA SERVONO I MOCK?A COSA SERVONO I MOCK?
testare le classi in isolamento
verificare che certi metodi vengano chiamati
verificare i parametri con cui i metodi sono chiamati
specificare i valori di ritorno dei metodi
QUANDO USARE I MOCKQUANDO USARE I MOCK
valori non deterministici (es. orario)
condizioni difficili da ricreare (es. errori di rete)
metodi che rallentano i test (es. accesso al db)
evitare di aggiungere metodi per ispezionare lo
stato
MOCK DI INTERFACCIAMOCK DI INTERFACCIA
class Foo {
public:
virtual ~Foo() = default;
virtual int GetSize() const = 0;
virtual std::string Describe(const char* name) = 0;
virtual std::string Describe(int type) = 0;
virtual bool Process(Bar elem, int count) = 0;
};
class MockFoo : public Foo {
public:
MOCK_CONST_METHOD0(GetSize, int());
MOCK_METHOD1(Describe, std::string(const char* name));
MOCK_METHOD1(Describe, std::string(int type));
MOCK_METHOD2(Process, bool(Bar elem, int count));
};
// default is NaggyMock (prints a warning)
NiceMock<MockFoo> nice_foo; // ignores uninteresting calls
StrictMock<MockFoo> strict_foo; // fails on uninteresting call
USO DI MOCKUSO DI MOCK
TEST(BarTest, DoesThis) {
MockFoo foo;
ON_CALL(foo, GetSize())
.WillByDefault(Return(1));
// ... other default actions ...
EXPECT_CALL(foo, Describe(5))
.Times(3)
.WillRepeatedly(Return("Category 5"));
// ... other expectations ...
EXPECT_EQ("good", MyProductionFunction(&foo));
}
I CICLI DEL TDDI CICLI DEL TDD
esterno (test di accettazione)
interno (unit test)
BANK KATABANK KATA
-
Creare una semplice applicazione bancaria con le
seguenti funzionalità:
deposito su un conto corrente
prelievo da un conto corrente
stampare i movimenti del conto corrente sul
terminale
Implementazione Java Screencast
CRITERI DI ACCETTAZIONECRITERI DI ACCETTAZIONE
La stampa dei movimenti ha il seguente formato:
DATA | IMPORTO | SALDO
10/04/2014 | 500 | 1400
02/04/2014 | -100 | 900
01/04/2014 | 1000 | 1000
VINCOLIVINCOLI
utilizzare una classe con questa struttura:
non puoi aggiungere metodi pubblici alla classe
per semplicità usiamo int per gli importi e std::string
per le date
la spaziatura nella stampa dei movimenti non è
vincolante
class ContoCorrente
{
public:
void Deposita(int importo);
void Preleva(int importo);
void StampaMovimenti();
};

More Related Content

Similar to Googletest, tdd e mock

Unit testing 101
Unit testing 101Unit testing 101
Unit testing 101
Daniel Londero
 
Introduzione al Test Driven Development
Introduzione al Test Driven DevelopmentIntroduzione al Test Driven Development
Introduzione al Test Driven Development
Ennio Masi
 
Android Test Driven Development
Android Test Driven DevelopmentAndroid Test Driven Development
Android Test Driven Developmentsazilla
 
Android Test Driven Development
Android Test Driven DevelopmentAndroid Test Driven Development
Android Test Driven Developmentsazilla
 
Javaday 2006: Java 5
Javaday 2006: Java 5Javaday 2006: Java 5
Javaday 2006: Java 5
Matteo Baccan
 
Applicazioni native in java
Applicazioni native in javaApplicazioni native in java
Applicazioni native in java
Federico Paparoni
 
Presentazione della Tesi di Laurea Specialistica : STRUMENTI PER LA GENERAZIO...
Presentazione della Tesi di Laurea Specialistica : STRUMENTI PER LA GENERAZIO...Presentazione della Tesi di Laurea Specialistica : STRUMENTI PER LA GENERAZIO...
Presentazione della Tesi di Laurea Specialistica : STRUMENTI PER LA GENERAZIO...
Boymix81
 
Tdd.Every.Where.21012012
Tdd.Every.Where.21012012Tdd.Every.Where.21012012
Tdd.Every.Where.21012012LEGALDESK
 
Junit tutorial
Junit tutorialJunit tutorial
Junit tutorial
fdesimone
 
Corso pratico di C# - 2013
Corso pratico di C# - 2013Corso pratico di C# - 2013
Corso pratico di C# - 2013
Matteo Valoriani
 
PowerMock TDD User Group Milano
PowerMock TDD User Group MilanoPowerMock TDD User Group Milano
PowerMock TDD User Group Milano
Massimo Groppelli
 
The Hitchhiker's Guide to testable code: semplici regole per scrivere codice ...
The Hitchhiker's Guide to testable code: semplici regole per scrivere codice ...The Hitchhiker's Guide to testable code: semplici regole per scrivere codice ...
The Hitchhiker's Guide to testable code: semplici regole per scrivere codice ...
Davide Cerbo
 
Py a1 python-unit_testing
Py a1 python-unit_testingPy a1 python-unit_testing
Py a1 python-unit_testingMajong DevJfu
 
Il testing con zend framework
Il testing con zend frameworkIl testing con zend framework
Il testing con zend framework
Zend by Rogue Wave Software
 
Dominare il codice legacy
Dominare il codice legacyDominare il codice legacy
Dominare il codice legacyTommaso Torti
 
Clean android code
Clean android codeClean android code
Clean android code
firenze-gtug
 

Similar to Googletest, tdd e mock (20)

Unit testing 101
Unit testing 101Unit testing 101
Unit testing 101
 
Introduzione al Test Driven Development
Introduzione al Test Driven DevelopmentIntroduzione al Test Driven Development
Introduzione al Test Driven Development
 
Android Test Driven Development
Android Test Driven DevelopmentAndroid Test Driven Development
Android Test Driven Development
 
Android Test Driven Development
Android Test Driven DevelopmentAndroid Test Driven Development
Android Test Driven Development
 
Testing
TestingTesting
Testing
 
Javaday 2006: Java 5
Javaday 2006: Java 5Javaday 2006: Java 5
Javaday 2006: Java 5
 
Applicazioni native in java
Applicazioni native in javaApplicazioni native in java
Applicazioni native in java
 
Presentazione della Tesi di Laurea Specialistica : STRUMENTI PER LA GENERAZIO...
Presentazione della Tesi di Laurea Specialistica : STRUMENTI PER LA GENERAZIO...Presentazione della Tesi di Laurea Specialistica : STRUMENTI PER LA GENERAZIO...
Presentazione della Tesi di Laurea Specialistica : STRUMENTI PER LA GENERAZIO...
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
Tdd.Every.Where.21012012
Tdd.Every.Where.21012012Tdd.Every.Where.21012012
Tdd.Every.Where.21012012
 
Junit tutorial
Junit tutorialJunit tutorial
Junit tutorial
 
Corso pratico di C# - 2013
Corso pratico di C# - 2013Corso pratico di C# - 2013
Corso pratico di C# - 2013
 
PowerMock TDD User Group Milano
PowerMock TDD User Group MilanoPowerMock TDD User Group Milano
PowerMock TDD User Group Milano
 
The Hitchhiker's Guide to testable code: semplici regole per scrivere codice ...
The Hitchhiker's Guide to testable code: semplici regole per scrivere codice ...The Hitchhiker's Guide to testable code: semplici regole per scrivere codice ...
The Hitchhiker's Guide to testable code: semplici regole per scrivere codice ...
 
Py a1 python-unit_testing
Py a1 python-unit_testingPy a1 python-unit_testing
Py a1 python-unit_testing
 
Il testing con zend framework
Il testing con zend frameworkIl testing con zend framework
Il testing con zend framework
 
Il testing con zend framework
Il testing con zend frameworkIl testing con zend framework
Il testing con zend framework
 
Dominare il codice legacy
Dominare il codice legacyDominare il codice legacy
Dominare il codice legacy
 
Java lezione1
Java lezione1Java lezione1
Java lezione1
 
Clean android code
Clean android codeClean android code
Clean android code
 

Googletest, tdd e mock

  • 1. SOMMARIOSOMMARIO Test automatici e TDD Installazione e utilizzo di googletest Test con googlemock Risolviamo un code kata Domande
  • 2. YURI VALENTINIYURI VALENTINI SW Windows e Linux FW schede embedded Linguaggi: C/C++, C#, Python Ambiti: Videoconferenza e VOIP Automazione industriale Biomedicale yuroller@gmail.com https://github.com/yuroller
  • 3. TESTING VS CHECKINGTESTING VS CHECKING Richiede persona senziente Automatizzabile Fa scoprire nuove cose Conferma le nostre assunzioni Fa richieste inedite Fa sempre le stesse richieste Esplorazione e scoperta di nuove cose Assicura che il programma funzioni Michael Bolton blog post
  • 4. INSTALLAZIONEINSTALLAZIONE VCPKGVCPKG > git clone https://github.com/Microsoft/vcpkg.git > cd vcpkg > bootstrap-vcpkg.bat (admin)> vcpkg integrate install > vcpkg install gtest:x64-windows
  • 5. VISUAL STUDIOVISUAL STUDIO Creare una solution Creare il progetto di test (console) Aggiungere: Definire: Linker → Debugging: /DEBUG:FULL Rimuovere: main() gtest{d}.lib;gtest_main{d}.lib _SILENCE_TR1_NAMESPACE_DEPRECATION_WARNI
  • 6. PRIMO TESTPRIMO TEST #include <gtest/gtest.h> TEST(TrivialTest, ChecksWeCanTest) { EXPECT_EQ(0, 1); }
  • 7. LINUXLINUX Installare strumenti sviluppo e cmake Ottenere sorgenti gtest Makefile: $ mkdir build $ cd build $ cmake .. $ make && make install TestApp: TestApp.cpp g++ -g -Wall -o TestApp TestApp.cpp -I../install/include -L../install/lib -lgtest -lgtest_main -lpthread .PHONY: clean clean: rm TestApp
  • 8. GTEST_MAIN.CCGTEST_MAIN.CC #include <stdio.h> #include "gtest/gtest.h" GTEST_API_ int main(int argc, char **argv) { printf("Running main() from gtest_main.ccn"); testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
  • 9. ESEGUIRE I TESTESEGUIRE I TEST Linea di comando Test runner esterno Visual Studio Test Explorer
  • 10. ASSERZIONIASSERZIONI ASSERT_*, EXPECT_* TRUE, FALSE EQ, NE, LT, LE, GT, GE C-strings: STREQ, STRNE Immediato: FAIL(), SUCCEED() Eccezioni: THROW, ANY_THROW, NO_THROW FLOAT_EQ, DOUBLE_EQ, NEAR Windows: HRESULT_SUCCEEDED, HRESULT_FAILED Documentazione gtest
  • 11. ASSERZIONI GMOCKASSERZIONI GMOCK ASSERT_THAT, EXPECT_THAT Generici: Eq, Ge, IsNull, NotNull FP: FloatEq, DoubleEq, FloatNear, DoubleNear String: MatchesRegex, StartsWith, HasSubstr stl: Eq, Contains, IsEmpty, SizeIs std::pair → Pair - std::map → Key Documentazione gmock
  • 12. TEST FIXTURETEST FIXTURE class BarTest : public ::testing::Test { protected: BarTest() { instance_resource_ = new ...; // inizialization } ~BarTest() { delete instance_resource_; } // virtual void SetUp() // virtual void TearDown() T* instance_resource_; // reacreated each test }; TEST_F(BarTest, Test0) { ... }
  • 13. RISORSA CONDIVISARISORSA CONDIVISA class FooTest : public ::testing::Test { protected: static void SetUpTestCase() { shared_resource_ = new ...; } static void TearDownTestCase() { delete shared_resource_; shared_resource_ = nullptr; } static T* shared_resource_; // Shared expensive resource }; T* FooTest::shared_resource_ = nullptr; TEST_F(FooTest, Test1) { ... }
  • 14. VARIEVARIE DISABLED_ death test global fixtures test parametrici (TEST_P) esecuzione parallela esecuzione ordine casuale filtri per esecuzione test
  • 16. MODELLO 3A PER TESTMODELLO 3A PER TEST Arrange Act Assert
  • 17. NOMI DEI TESTNOMI DEI TEST Ognuno ha la sua convenzione Test Case: {nome_classe/scenario}Test Test Name: {descrizione_del_test} Alcuni usano: MethodName_GivenConditions _WhenThisHappens_ThenThisisExpectedResult TEST(FactorialTest, HandlesZeroInput) sumOfTwoNumbers_givenTwoPositiveNumbers _WhenNumbersArePositive_ThenResultIsPositive()
  • 18. COSA TESTARECOSA TESTARE Coverage del codice sorgente Condizioni dell'if Input valido e input NON valido exception
  • 19. TDDTDD "TDD by Example" ‐ Kent Beck 1. Quickly add a test 2. Run all tests and see the new one fail 3. Make a little change 4. Run all tests and see them all succeed 5. Refactor to remove duplication
  • 20. REFACTORINGREFACTORING Rimuovi la duplicazione (DRY) Usa nomi appropriati Semplifica le classi/funzioni (SRP)
  • 21. STILE DI TESTSTILE DI TEST Classicista (Chicago/Detroit school) Mockista (London school) GOOS
  • 23. FAKEFAKE Fakes are objects that have working implementations, but not same as production one. Usually they take some shortcut and have simplified version of production code.
  • 24. STUBSTUB Stub is an object that holds predefined data and uses it to answer calls during tests. It is used when we cannot or don’t want to involve objects that would answer with real data or have undesirable side effects.
  • 25. MOCKMOCK Mocks are objects that register calls they receive. In test assertion we can verify on Mocks that all expected actions were performed.
  • 26. A COSA SERVONO I MOCK?A COSA SERVONO I MOCK? testare le classi in isolamento verificare che certi metodi vengano chiamati verificare i parametri con cui i metodi sono chiamati specificare i valori di ritorno dei metodi
  • 27. QUANDO USARE I MOCKQUANDO USARE I MOCK valori non deterministici (es. orario) condizioni difficili da ricreare (es. errori di rete) metodi che rallentano i test (es. accesso al db) evitare di aggiungere metodi per ispezionare lo stato
  • 28. MOCK DI INTERFACCIAMOCK DI INTERFACCIA class Foo { public: virtual ~Foo() = default; virtual int GetSize() const = 0; virtual std::string Describe(const char* name) = 0; virtual std::string Describe(int type) = 0; virtual bool Process(Bar elem, int count) = 0; }; class MockFoo : public Foo { public: MOCK_CONST_METHOD0(GetSize, int()); MOCK_METHOD1(Describe, std::string(const char* name)); MOCK_METHOD1(Describe, std::string(int type)); MOCK_METHOD2(Process, bool(Bar elem, int count)); }; // default is NaggyMock (prints a warning) NiceMock<MockFoo> nice_foo; // ignores uninteresting calls StrictMock<MockFoo> strict_foo; // fails on uninteresting call
  • 29. USO DI MOCKUSO DI MOCK TEST(BarTest, DoesThis) { MockFoo foo; ON_CALL(foo, GetSize()) .WillByDefault(Return(1)); // ... other default actions ... EXPECT_CALL(foo, Describe(5)) .Times(3) .WillRepeatedly(Return("Category 5")); // ... other expectations ... EXPECT_EQ("good", MyProductionFunction(&foo)); }
  • 30. I CICLI DEL TDDI CICLI DEL TDD esterno (test di accettazione) interno (unit test)
  • 31. BANK KATABANK KATA - Creare una semplice applicazione bancaria con le seguenti funzionalità: deposito su un conto corrente prelievo da un conto corrente stampare i movimenti del conto corrente sul terminale Implementazione Java Screencast
  • 32. CRITERI DI ACCETTAZIONECRITERI DI ACCETTAZIONE La stampa dei movimenti ha il seguente formato: DATA | IMPORTO | SALDO 10/04/2014 | 500 | 1400 02/04/2014 | -100 | 900 01/04/2014 | 1000 | 1000
  • 33. VINCOLIVINCOLI utilizzare una classe con questa struttura: non puoi aggiungere metodi pubblici alla classe per semplicità usiamo int per gli importi e std::string per le date la spaziatura nella stampa dei movimenti non è vincolante class ContoCorrente { public: void Deposita(int importo); void Preleva(int importo); void StampaMovimenti(); };