SlideShare una empresa de Scribd logo
1 de 38
Testing your code

                                                       For Java developers


                                                            Anna Khasanova
                                           Anna.Khasanova@exigenservices.com


27 March 2013
            Exigen Services confidential                     Exigen Services confidential
Agenda




•   Testing basics
•   TDD approach
•   Testing in action
•   Best practices



        Exigen Services confidential   2
What is a test? Why do we need it?




• What is test?
• Why do we need testing?
• Automation




      Exigen Services confidential   3
Automatic testing



Write once run often:
• Write test once
• Run frequently:
  • After each change
  • Continuous integration
• No human input


      Exigen Services confidential   4
What is Test Driven Development?

                                            TDD THEORY



Exigen Services confidential                                  5
Test Driven Development




• Software development approach
• Test before code
• Test - code requirements




      Exigen Services confidential   6
Advantages




• Increase requirements quality
• Increase code quality
• No unnecessary code




      Exigen Services confidential   7
New change request?
Design

  Write      Test succeeds
  test

              Test fails
Run test
                                    Write        Test fails
                                    code
Whole story covered
                                                    Test
                                                  succeeds
                                Run test
                                                              Refactor   Test fails
                                                               code
                                          All tests succeed
                                                                           Test
                                                                         succeeds
                                                              Run test
           Exigen Services confidential                                               8
Bugfix?



•   Get bug report
•   Turn it into a test
•   Test should fail
•   Fix bug
•   Test should pass



         Exigen Services confidential   9
How should I work?
                                How to write tests?

                               THE PRACTICE



Exigen Services confidential                     10
What is Unit Test?




• Automated test for
  • One business unit
  • One business case
• Isolated




      Exigen Services confidential   11
Unit Test is




• Small
• Fast
• Self documented




       Exigen Services confidential   12
3 parts of Unit-test

unitTest() {

    // set preconditions: “arrange”

    // call tested method: “act”

    // assert results are as expected: “assert”
}

        Exigen Services confidential          13
Unit-Test libraries



• xUnit – collective naming:
  dbUnit, htmlUnit, qUnit, etc.
• Java: jUnit
• Java: TestNG
• Javascript: jasmine



       Exigen Services confidential   14
Example of TDD



Telephone field validator:
  • Allowed characters:
     • numbers: [0-9]
     • minus, space: “-” , “ ”
  • Length: 10 digits (ignore spaces and minuses)
  • Leading and trailing spaces are allowed



       Exigen Services confidential             15
Mock all dependencies

                                     REAL LIFE



Exigen Services confidential                      16
We have a problem!




• Method uses web service
• or some other class/function
• We don’t want to test it




      Exigen Services confidential   17
Mock




• Fake implementation
• We set what mock returns
• Useful for unit-testing




       Exigen Services confidential   18
Mock libraries




• Mockito
• EasyMock
• jMock




      Exigen Services confidential   19
Example



        PicturesService
    +getSquarePictures()


                                      Repository
                                    +getAllPictures()




     Exigen Services confidential                       20
Example

@Test
 public void testGetSquarePicturesEmptyResult() {
   PicturesService testedService = new PicturesService();

      Repository repository = mock(Repository.class);
      //create fake Repository, returning empty list of pictures
      when(repository.getAllPictures())
              .thenReturn(Collections.<Picture>emptyList());
      testedService.setRepository(repository);

      Set<Picture> result = testedService.getSquarePictures();

      assertTrue(result.isEmpty());
  }

            Exigen Services confidential                           21
How to verify external calls?




• What to do if:
  • Tested method should call externals
  • We need to ensure that it was called?


• Mocks scenario verification



      Exigen Services confidential          22
Example

@Test
 public void testDeleteSquarePicturesEmptyResult() {
   PicturesService testedService = new PicturesService();

      Repository repository = mock(Repository.class);
      Mockito.when(repository.getAllPictures())
                 .thenReturn(Collections.<Picture>emptyList());
      testedService.setRepository(repository);

      testedService.deleteSquarePictures();

      verify(repository, never()).deletePictures(any());
  }

           Exigen Services confidential                           23
How to verify arguments?



• What to do if:
  • Mocked method is called with parameters
  • We need to test passed parameters?


• Argument Captor
• Matchers


      Exigen Services confidential            24
Example

@Test
 public void testDeleteSquarePictures_captor() {
   …

      ArgumentCaptor<Iterable> captor =
                       ArgumentCaptor.forClass(Iterable.class);

      verify(repository).deletePictures(captor.capture());

      Iterable<Picture> result = captor.getValue();

      …
  }

           Exigen Services confidential                           25
How to verify exceptional cases?

• What to do if:
  • Tested method should throw exception in
    some case
  • We need to test this case?


• Expected exceptions
 @Test(expected = IllegalArgumentException.class)
 public void testFactorialNegative() {
   Factorial.factorial(-2);
 }



        Exigen Services confidential                26
How to verify exceptional cases?


• What to do if:
  • We need to test time of execution?


• Timeout parameter
 @Test(timeout = 1000)
 public void infinity() {
   while (true) ;
 }




         Exigen Services confidential    27
OTHER USEFUL FEATURES



Exigen Services confidential             28
Other features: matchers



                 Matchers
• when(…), verify(…)
• assertThat(…)

• See hamcrest library
• Write your own


      Exigen Services confidential   29
Other features: runners



                               Test runners
• @RunWith
  • Spring: SpringJUnit4ClassRunner
  • Parameterized
  • Any other




      Exigen Services confidential            30
To sum this all up…

                               SUMMARY. GUIDELINES.



Exigen Services confidential                             31
Coverage




• Coverage: what needs to be covered
• Setters-getters




      Exigen Services confidential     32
Above all




1. Understand requirements
2. Commit your understanding
  • Java docs
  • Any other




      Exigen Services confidential   33
Unit test




• One test – one case
• Each use case – covered
• Unit test != trash




       Exigen Services confidential   34
Write testable code




• Statics are evil
• Extract interfaces
• One method must not do “everything”




      Exigen Services confidential      35
Use framework’s features




•   Parameterized tests
•   Expected exceptions, timeouts
•   Mock objects scenarios
•   Matchers



        Exigen Services confidential   36
Finally




• Automatic testing – difficult to start, but…
• Don’t give up!




          Exigen Services confidential           37
Your turn

                               QUESTIONS?



Exigen Services confidential               38

Más contenido relacionado

La actualidad más candente

Automated testing of ASP .Net Core applications
Automated testing of ASP .Net Core applications Automated testing of ASP .Net Core applications
Automated testing of ASP .Net Core applications nispas
 
DSR Testing (Part 2)
DSR Testing (Part 2)DSR Testing (Part 2)
DSR Testing (Part 2)Steve Upton
 
Efficient JavaScript Unit Testing, March 2013
Efficient JavaScript Unit Testing, March 2013Efficient JavaScript Unit Testing, March 2013
Efficient JavaScript Unit Testing, March 2013Hazem Saleh
 
Example of TAF with batch execution of test cases
 Example of TAF with batch execution of test cases  Example of TAF with batch execution of test cases
Example of TAF with batch execution of test cases COMAQA.BY
 
Testing Spring Boot Applications
Testing Spring Boot ApplicationsTesting Spring Boot Applications
Testing Spring Boot ApplicationsVMware Tanzu
 
Developers Testing - Girl Code at bloomon
Developers Testing - Girl Code at bloomonDevelopers Testing - Girl Code at bloomon
Developers Testing - Girl Code at bloomonIneke Scheffers
 
Spring Testing Features
Spring Testing FeaturesSpring Testing Features
Spring Testing FeaturesGil Zilberfeld
 
Testing with Spring: An Introduction
Testing with Spring: An IntroductionTesting with Spring: An Introduction
Testing with Spring: An IntroductionSam Brannen
 
VT.NET 20160411: An Intro to Test Driven Development (TDD)
VT.NET 20160411: An Intro to Test Driven Development (TDD)VT.NET 20160411: An Intro to Test Driven Development (TDD)
VT.NET 20160411: An Intro to Test Driven Development (TDD)Rob Hale
 
TDD reloaded - JUGTAA 24 Ottobre 2012
TDD reloaded - JUGTAA 24 Ottobre 2012TDD reloaded - JUGTAA 24 Ottobre 2012
TDD reloaded - JUGTAA 24 Ottobre 2012Pietro Di Bello
 
Quickly testing legacy code
Quickly testing legacy codeQuickly testing legacy code
Quickly testing legacy codeClare Macrae
 
Testing in FrontEnd World by Nikita Galkin
Testing in FrontEnd World by Nikita GalkinTesting in FrontEnd World by Nikita Galkin
Testing in FrontEnd World by Nikita GalkinSigma Software
 
Unit Testing Best Practices
Unit Testing Best PracticesUnit Testing Best Practices
Unit Testing Best PracticesTomaš Maconko
 
Pitfalls Of Tdd Adoption by Bartosz Bankowski
Pitfalls Of Tdd Adoption by Bartosz BankowskiPitfalls Of Tdd Adoption by Bartosz Bankowski
Pitfalls Of Tdd Adoption by Bartosz BankowskiAgileee
 
Test driven development and unit testing with examples in C++
Test driven development and unit testing with examples in C++Test driven development and unit testing with examples in C++
Test driven development and unit testing with examples in C++Hong Le Van
 
Into The Box 2018 | Assert control over your legacy applications
Into The Box 2018 | Assert control over your legacy applicationsInto The Box 2018 | Assert control over your legacy applications
Into The Box 2018 | Assert control over your legacy applicationsOrtus Solutions, Corp
 

La actualidad más candente (20)

Angular Unit Testing
Angular Unit TestingAngular Unit Testing
Angular Unit Testing
 
TDD & BDD
TDD & BDDTDD & BDD
TDD & BDD
 
Automated testing of ASP .Net Core applications
Automated testing of ASP .Net Core applications Automated testing of ASP .Net Core applications
Automated testing of ASP .Net Core applications
 
Unit Tesing in iOS
Unit Tesing in iOSUnit Tesing in iOS
Unit Tesing in iOS
 
DSR Testing (Part 2)
DSR Testing (Part 2)DSR Testing (Part 2)
DSR Testing (Part 2)
 
Efficient JavaScript Unit Testing, March 2013
Efficient JavaScript Unit Testing, March 2013Efficient JavaScript Unit Testing, March 2013
Efficient JavaScript Unit Testing, March 2013
 
Example of TAF with batch execution of test cases
 Example of TAF with batch execution of test cases  Example of TAF with batch execution of test cases
Example of TAF with batch execution of test cases
 
Testing Spring Boot Applications
Testing Spring Boot ApplicationsTesting Spring Boot Applications
Testing Spring Boot Applications
 
Developers Testing - Girl Code at bloomon
Developers Testing - Girl Code at bloomonDevelopers Testing - Girl Code at bloomon
Developers Testing - Girl Code at bloomon
 
Spring Testing Features
Spring Testing FeaturesSpring Testing Features
Spring Testing Features
 
Testing with Spring: An Introduction
Testing with Spring: An IntroductionTesting with Spring: An Introduction
Testing with Spring: An Introduction
 
VT.NET 20160411: An Intro to Test Driven Development (TDD)
VT.NET 20160411: An Intro to Test Driven Development (TDD)VT.NET 20160411: An Intro to Test Driven Development (TDD)
VT.NET 20160411: An Intro to Test Driven Development (TDD)
 
TDD reloaded - JUGTAA 24 Ottobre 2012
TDD reloaded - JUGTAA 24 Ottobre 2012TDD reloaded - JUGTAA 24 Ottobre 2012
TDD reloaded - JUGTAA 24 Ottobre 2012
 
Quickly testing legacy code
Quickly testing legacy codeQuickly testing legacy code
Quickly testing legacy code
 
TestNG vs. JUnit4
TestNG vs. JUnit4TestNG vs. JUnit4
TestNG vs. JUnit4
 
Testing in FrontEnd World by Nikita Galkin
Testing in FrontEnd World by Nikita GalkinTesting in FrontEnd World by Nikita Galkin
Testing in FrontEnd World by Nikita Galkin
 
Unit Testing Best Practices
Unit Testing Best PracticesUnit Testing Best Practices
Unit Testing Best Practices
 
Pitfalls Of Tdd Adoption by Bartosz Bankowski
Pitfalls Of Tdd Adoption by Bartosz BankowskiPitfalls Of Tdd Adoption by Bartosz Bankowski
Pitfalls Of Tdd Adoption by Bartosz Bankowski
 
Test driven development and unit testing with examples in C++
Test driven development and unit testing with examples in C++Test driven development and unit testing with examples in C++
Test driven development and unit testing with examples in C++
 
Into The Box 2018 | Assert control over your legacy applications
Into The Box 2018 | Assert control over your legacy applicationsInto The Box 2018 | Assert control over your legacy applications
Into The Box 2018 | Assert control over your legacy applications
 

Destacado

Celebrate your Path (financial wellness class)
Celebrate your Path (financial wellness class)Celebrate your Path (financial wellness class)
Celebrate your Path (financial wellness class)Tony Hollenback
 
De verkleuring van armoede (bijlage 3)
De verkleuring van armoede (bijlage 3)De verkleuring van armoede (bijlage 3)
De verkleuring van armoede (bijlage 3)annekesomers
 
syed SALEEM .final
syed SALEEM .finalsyed SALEEM .final
syed SALEEM .finalSYED SALEEM
 
Timoshenko resistencia de materiales-tomo ii (2)
Timoshenko resistencia de materiales-tomo ii (2)Timoshenko resistencia de materiales-tomo ii (2)
Timoshenko resistencia de materiales-tomo ii (2)efrak91
 
C 14-dce-101-english
C 14-dce-101-englishC 14-dce-101-english
C 14-dce-101-englishSrinivasa Rao
 
Signals and Systems by Alan v.oppenheim, alan s. willsky &amp; s.hamid nawab(...
Signals and Systems by Alan v.oppenheim, alan s. willsky &amp; s.hamid nawab(...Signals and Systems by Alan v.oppenheim, alan s. willsky &amp; s.hamid nawab(...
Signals and Systems by Alan v.oppenheim, alan s. willsky &amp; s.hamid nawab(...rbatec
 
Big Data - Opportunities for PMR Operators and Public Safety Organizations
Big Data - Opportunities for PMR Operators and Public Safety OrganizationsBig Data - Opportunities for PMR Operators and Public Safety Organizations
Big Data - Opportunities for PMR Operators and Public Safety OrganizationsSecure Land Communications
 
Clase fracturas+faciales
Clase fracturas+facialesClase fracturas+faciales
Clase fracturas+facialesvaca120378
 
Ch 4: Footprinting and Social Engineering
Ch 4: Footprinting and Social EngineeringCh 4: Footprinting and Social Engineering
Ch 4: Footprinting and Social EngineeringSam Bowne
 
Vamos a prender las provincias y sus respectivas
Vamos a prender las provincias y sus respectivasVamos a prender las provincias y sus respectivas
Vamos a prender las provincias y sus respectivasromerotati
 

Destacado (13)

Celebrate your Path (financial wellness class)
Celebrate your Path (financial wellness class)Celebrate your Path (financial wellness class)
Celebrate your Path (financial wellness class)
 
De verkleuring van armoede (bijlage 3)
De verkleuring van armoede (bijlage 3)De verkleuring van armoede (bijlage 3)
De verkleuring van armoede (bijlage 3)
 
Língua Portuguesa
Língua PortuguesaLíngua Portuguesa
Língua Portuguesa
 
syed SALEEM .final
syed SALEEM .finalsyed SALEEM .final
syed SALEEM .final
 
Designing Testable Software
Designing Testable SoftwareDesigning Testable Software
Designing Testable Software
 
Timoshenko resistencia de materiales-tomo ii (2)
Timoshenko resistencia de materiales-tomo ii (2)Timoshenko resistencia de materiales-tomo ii (2)
Timoshenko resistencia de materiales-tomo ii (2)
 
C 14-dce-101-english
C 14-dce-101-englishC 14-dce-101-english
C 14-dce-101-english
 
Signals and Systems by Alan v.oppenheim, alan s. willsky &amp; s.hamid nawab(...
Signals and Systems by Alan v.oppenheim, alan s. willsky &amp; s.hamid nawab(...Signals and Systems by Alan v.oppenheim, alan s. willsky &amp; s.hamid nawab(...
Signals and Systems by Alan v.oppenheim, alan s. willsky &amp; s.hamid nawab(...
 
Big Data - Opportunities for PMR Operators and Public Safety Organizations
Big Data - Opportunities for PMR Operators and Public Safety OrganizationsBig Data - Opportunities for PMR Operators and Public Safety Organizations
Big Data - Opportunities for PMR Operators and Public Safety Organizations
 
RADIOLOGIA EN REHABILITACION ORAL
RADIOLOGIA EN REHABILITACION ORALRADIOLOGIA EN REHABILITACION ORAL
RADIOLOGIA EN REHABILITACION ORAL
 
Clase fracturas+faciales
Clase fracturas+facialesClase fracturas+faciales
Clase fracturas+faciales
 
Ch 4: Footprinting and Social Engineering
Ch 4: Footprinting and Social EngineeringCh 4: Footprinting and Social Engineering
Ch 4: Footprinting and Social Engineering
 
Vamos a prender las provincias y sus respectivas
Vamos a prender las provincias y sus respectivasVamos a prender las provincias y sus respectivas
Vamos a prender las provincias y sus respectivas
 

Similar a Testing your code

Rethinking Testing
Rethinking TestingRethinking Testing
Rethinking Testingpdejuan
 
Renaissance of JUnit - Introduction to JUnit 5
Renaissance of JUnit - Introduction to JUnit 5Renaissance of JUnit - Introduction to JUnit 5
Renaissance of JUnit - Introduction to JUnit 5Jimmy Lu
 
When assertthat(you).understandUnitTesting() fails
When assertthat(you).understandUnitTesting() failsWhen assertthat(you).understandUnitTesting() fails
When assertthat(you).understandUnitTesting() failsMartin Skurla
 
Unit testing for Cocoa developers
Unit testing for Cocoa developersUnit testing for Cocoa developers
Unit testing for Cocoa developersGraham Lee
 
Qt test framework
Qt test frameworkQt test framework
Qt test frameworkICS
 
Episode 5 - Writing unit tests in Salesforce
Episode 5 - Writing unit tests in SalesforceEpisode 5 - Writing unit tests in Salesforce
Episode 5 - Writing unit tests in SalesforceJitendra Zaa
 
Testing JavaScript
Testing JavaScriptTesting JavaScript
Testing JavaScriptdhtml
 
An Introduction to Unit Test Using NUnit
An Introduction to Unit Test Using NUnitAn Introduction to Unit Test Using NUnit
An Introduction to Unit Test Using NUnitweili_at_slideshare
 
Jest: Frontend Testing leicht gemacht @EnterJS2018
Jest: Frontend Testing leicht gemacht @EnterJS2018Jest: Frontend Testing leicht gemacht @EnterJS2018
Jest: Frontend Testing leicht gemacht @EnterJS2018Holger Grosse-Plankermann
 
PuppetConf 2017: Test First Approach for Puppet on Windows- Miro Sommer, Hiscox
PuppetConf 2017: Test First Approach for Puppet on Windows- Miro Sommer, HiscoxPuppetConf 2017: Test First Approach for Puppet on Windows- Miro Sommer, Hiscox
PuppetConf 2017: Test First Approach for Puppet on Windows- Miro Sommer, HiscoxPuppet
 
Iasi code camp 20 april 2013 marian chicu - database unit tests in the sql se...
Iasi code camp 20 april 2013 marian chicu - database unit tests in the sql se...Iasi code camp 20 april 2013 marian chicu - database unit tests in the sql se...
Iasi code camp 20 april 2013 marian chicu - database unit tests in the sql se...Codecamp Romania
 
Taking a Test Drive: iOS Dev UK guide to TDD
Taking a Test Drive: iOS Dev UK guide to TDDTaking a Test Drive: iOS Dev UK guide to TDD
Taking a Test Drive: iOS Dev UK guide to TDDGraham Lee
 
Implementing Test Automation in Agile Projects
Implementing Test Automation in Agile ProjectsImplementing Test Automation in Agile Projects
Implementing Test Automation in Agile ProjectsDominik Dary
 
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
 

Similar a Testing your code (20)

Testing your code
Testing your codeTesting your code
Testing your code
 
Rethinking Testing
Rethinking TestingRethinking Testing
Rethinking Testing
 
Renaissance of JUnit - Introduction to JUnit 5
Renaissance of JUnit - Introduction to JUnit 5Renaissance of JUnit - Introduction to JUnit 5
Renaissance of JUnit - Introduction to JUnit 5
 
When assertthat(you).understandUnitTesting() fails
When assertthat(you).understandUnitTesting() failsWhen assertthat(you).understandUnitTesting() fails
When assertthat(you).understandUnitTesting() fails
 
Unit testing for Cocoa developers
Unit testing for Cocoa developersUnit testing for Cocoa developers
Unit testing for Cocoa developers
 
Qt test framework
Qt test frameworkQt test framework
Qt test framework
 
Episode 5 - Writing unit tests in Salesforce
Episode 5 - Writing unit tests in SalesforceEpisode 5 - Writing unit tests in Salesforce
Episode 5 - Writing unit tests in Salesforce
 
Testing JavaScript
Testing JavaScriptTesting JavaScript
Testing JavaScript
 
Unit testing basics
Unit testing basicsUnit testing basics
Unit testing basics
 
Test driven development
Test driven developmentTest driven development
Test driven development
 
Building XWiki
Building XWikiBuilding XWiki
Building XWiki
 
Testing Angular
Testing AngularTesting Angular
Testing Angular
 
Testing Tools Classroom Training
Testing Tools Classroom TrainingTesting Tools Classroom Training
Testing Tools Classroom Training
 
An Introduction to Unit Test Using NUnit
An Introduction to Unit Test Using NUnitAn Introduction to Unit Test Using NUnit
An Introduction to Unit Test Using NUnit
 
Jest: Frontend Testing leicht gemacht @EnterJS2018
Jest: Frontend Testing leicht gemacht @EnterJS2018Jest: Frontend Testing leicht gemacht @EnterJS2018
Jest: Frontend Testing leicht gemacht @EnterJS2018
 
PuppetConf 2017: Test First Approach for Puppet on Windows- Miro Sommer, Hiscox
PuppetConf 2017: Test First Approach for Puppet on Windows- Miro Sommer, HiscoxPuppetConf 2017: Test First Approach for Puppet on Windows- Miro Sommer, Hiscox
PuppetConf 2017: Test First Approach for Puppet on Windows- Miro Sommer, Hiscox
 
Iasi code camp 20 april 2013 marian chicu - database unit tests in the sql se...
Iasi code camp 20 april 2013 marian chicu - database unit tests in the sql se...Iasi code camp 20 april 2013 marian chicu - database unit tests in the sql se...
Iasi code camp 20 april 2013 marian chicu - database unit tests in the sql se...
 
Taking a Test Drive: iOS Dev UK guide to TDD
Taking a Test Drive: iOS Dev UK guide to TDDTaking a Test Drive: iOS Dev UK guide to TDD
Taking a Test Drive: iOS Dev UK guide to TDD
 
Implementing Test Automation in Agile Projects
Implementing Test Automation in Agile ProjectsImplementing Test Automation in Agile Projects
Implementing Test Automation in Agile Projects
 
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
 

Más de Return on Intelligence

Profsoux2014 presentation by Pavelchuk
Profsoux2014 presentation by PavelchukProfsoux2014 presentation by Pavelchuk
Profsoux2014 presentation by PavelchukReturn on Intelligence
 
Types of testing and their classification
Types of testing and their classificationTypes of testing and their classification
Types of testing and their classificationReturn on Intelligence
 
Service design principles and patterns
Service design principles and patternsService design principles and patterns
Service design principles and patternsReturn on Intelligence
 
Differences between Testing in Waterfall and Agile
Differences between Testing in Waterfall and AgileDifferences between Testing in Waterfall and Agile
Differences between Testing in Waterfall and AgileReturn on Intelligence
 
Организация внутренней системы обучения
Организация внутренней системы обученияОрганизация внутренней системы обучения
Организация внутренней системы обученияReturn on Intelligence
 
Shared position in a project: testing and analysis
Shared position in a project: testing and analysisShared position in a project: testing and analysis
Shared position in a project: testing and analysisReturn on Intelligence
 
Оценка задач выполняемых по итеративной разработке
Оценка задач выполняемых по итеративной разработкеОценка задач выполняемых по итеративной разработке
Оценка задач выполняемых по итеративной разработкеReturn on Intelligence
 
Successful interview for a young IT specialist
Successful interview for a young IT specialistSuccessful interview for a young IT specialist
Successful interview for a young IT specialistReturn on Intelligence
 

Más de Return on Intelligence (20)

Profsoux2014 presentation by Pavelchuk
Profsoux2014 presentation by PavelchukProfsoux2014 presentation by Pavelchuk
Profsoux2014 presentation by Pavelchuk
 
Agile Project Grows
Agile Project GrowsAgile Project Grows
Agile Project Grows
 
Types of testing and their classification
Types of testing and their classificationTypes of testing and their classification
Types of testing and their classification
 
Time Management
Time ManagementTime Management
Time Management
 
Service design principles and patterns
Service design principles and patternsService design principles and patterns
Service design principles and patterns
 
Differences between Testing in Waterfall and Agile
Differences between Testing in Waterfall and AgileDifferences between Testing in Waterfall and Agile
Differences between Testing in Waterfall and Agile
 
Windows Azure: Quick start
Windows Azure: Quick startWindows Azure: Quick start
Windows Azure: Quick start
 
Windows azurequickstart
Windows azurequickstartWindows azurequickstart
Windows azurequickstart
 
Организация внутренней системы обучения
Организация внутренней системы обученияОрганизация внутренней системы обучения
Организация внутренней системы обучения
 
Shared position in a project: testing and analysis
Shared position in a project: testing and analysisShared position in a project: testing and analysis
Shared position in a project: testing and analysis
 
Introduction to Business Etiquette
Introduction to Business EtiquetteIntroduction to Business Etiquette
Introduction to Business Etiquette
 
Agile Testing Process
Agile Testing ProcessAgile Testing Process
Agile Testing Process
 
Оценка задач выполняемых по итеративной разработке
Оценка задач выполняемых по итеративной разработкеОценка задач выполняемых по итеративной разработке
Оценка задач выполняемых по итеративной разработке
 
Meetings arranging
Meetings arrangingMeetings arranging
Meetings arranging
 
How to develop your creativity
How to develop your creativityHow to develop your creativity
How to develop your creativity
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
The art of project estimation
The art of project estimationThe art of project estimation
The art of project estimation
 
Successful interview for a young IT specialist
Successful interview for a young IT specialistSuccessful interview for a young IT specialist
Successful interview for a young IT specialist
 
Risk Management
Risk ManagementRisk Management
Risk Management
 
Resolving conflicts
Resolving conflictsResolving conflicts
Resolving conflicts
 

Testing your code

  • 1. Testing your code For Java developers Anna Khasanova Anna.Khasanova@exigenservices.com 27 March 2013 Exigen Services confidential Exigen Services confidential
  • 2. Agenda • Testing basics • TDD approach • Testing in action • Best practices Exigen Services confidential 2
  • 3. What is a test? Why do we need it? • What is test? • Why do we need testing? • Automation Exigen Services confidential 3
  • 4. Automatic testing Write once run often: • Write test once • Run frequently: • After each change • Continuous integration • No human input Exigen Services confidential 4
  • 5. What is Test Driven Development? TDD THEORY Exigen Services confidential 5
  • 6. Test Driven Development • Software development approach • Test before code • Test - code requirements Exigen Services confidential 6
  • 7. Advantages • Increase requirements quality • Increase code quality • No unnecessary code Exigen Services confidential 7
  • 8. New change request? Design Write Test succeeds test Test fails Run test Write Test fails code Whole story covered Test succeeds Run test Refactor Test fails code All tests succeed Test succeeds Run test Exigen Services confidential 8
  • 9. Bugfix? • Get bug report • Turn it into a test • Test should fail • Fix bug • Test should pass Exigen Services confidential 9
  • 10. How should I work? How to write tests? THE PRACTICE Exigen Services confidential 10
  • 11. What is Unit Test? • Automated test for • One business unit • One business case • Isolated Exigen Services confidential 11
  • 12. Unit Test is • Small • Fast • Self documented Exigen Services confidential 12
  • 13. 3 parts of Unit-test unitTest() { // set preconditions: “arrange” // call tested method: “act” // assert results are as expected: “assert” } Exigen Services confidential 13
  • 14. Unit-Test libraries • xUnit – collective naming: dbUnit, htmlUnit, qUnit, etc. • Java: jUnit • Java: TestNG • Javascript: jasmine Exigen Services confidential 14
  • 15. Example of TDD Telephone field validator: • Allowed characters: • numbers: [0-9] • minus, space: “-” , “ ” • Length: 10 digits (ignore spaces and minuses) • Leading and trailing spaces are allowed Exigen Services confidential 15
  • 16. Mock all dependencies REAL LIFE Exigen Services confidential 16
  • 17. We have a problem! • Method uses web service • or some other class/function • We don’t want to test it Exigen Services confidential 17
  • 18. Mock • Fake implementation • We set what mock returns • Useful for unit-testing Exigen Services confidential 18
  • 19. Mock libraries • Mockito • EasyMock • jMock Exigen Services confidential 19
  • 20. Example PicturesService +getSquarePictures() Repository +getAllPictures() Exigen Services confidential 20
  • 21. Example @Test public void testGetSquarePicturesEmptyResult() { PicturesService testedService = new PicturesService(); Repository repository = mock(Repository.class); //create fake Repository, returning empty list of pictures when(repository.getAllPictures()) .thenReturn(Collections.<Picture>emptyList()); testedService.setRepository(repository); Set<Picture> result = testedService.getSquarePictures(); assertTrue(result.isEmpty()); } Exigen Services confidential 21
  • 22. How to verify external calls? • What to do if: • Tested method should call externals • We need to ensure that it was called? • Mocks scenario verification Exigen Services confidential 22
  • 23. Example @Test public void testDeleteSquarePicturesEmptyResult() { PicturesService testedService = new PicturesService(); Repository repository = mock(Repository.class); Mockito.when(repository.getAllPictures()) .thenReturn(Collections.<Picture>emptyList()); testedService.setRepository(repository); testedService.deleteSquarePictures(); verify(repository, never()).deletePictures(any()); } Exigen Services confidential 23
  • 24. How to verify arguments? • What to do if: • Mocked method is called with parameters • We need to test passed parameters? • Argument Captor • Matchers Exigen Services confidential 24
  • 25. Example @Test public void testDeleteSquarePictures_captor() { … ArgumentCaptor<Iterable> captor = ArgumentCaptor.forClass(Iterable.class); verify(repository).deletePictures(captor.capture()); Iterable<Picture> result = captor.getValue(); … } Exigen Services confidential 25
  • 26. How to verify exceptional cases? • What to do if: • Tested method should throw exception in some case • We need to test this case? • Expected exceptions @Test(expected = IllegalArgumentException.class) public void testFactorialNegative() { Factorial.factorial(-2); } Exigen Services confidential 26
  • 27. How to verify exceptional cases? • What to do if: • We need to test time of execution? • Timeout parameter @Test(timeout = 1000) public void infinity() { while (true) ; } Exigen Services confidential 27
  • 28. OTHER USEFUL FEATURES Exigen Services confidential 28
  • 29. Other features: matchers Matchers • when(…), verify(…) • assertThat(…) • See hamcrest library • Write your own Exigen Services confidential 29
  • 30. Other features: runners Test runners • @RunWith • Spring: SpringJUnit4ClassRunner • Parameterized • Any other Exigen Services confidential 30
  • 31. To sum this all up… SUMMARY. GUIDELINES. Exigen Services confidential 31
  • 32. Coverage • Coverage: what needs to be covered • Setters-getters Exigen Services confidential 32
  • 33. Above all 1. Understand requirements 2. Commit your understanding • Java docs • Any other Exigen Services confidential 33
  • 34. Unit test • One test – one case • Each use case – covered • Unit test != trash Exigen Services confidential 34
  • 35. Write testable code • Statics are evil • Extract interfaces • One method must not do “everything” Exigen Services confidential 35
  • 36. Use framework’s features • Parameterized tests • Expected exceptions, timeouts • Mock objects scenarios • Matchers Exigen Services confidential 36
  • 37. Finally • Automatic testing – difficult to start, but… • Don’t give up! Exigen Services confidential 37
  • 38. Your turn QUESTIONS? Exigen Services confidential 38