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

More Related Content

PPTX
Testing your code
PDF
Unit Test your Views
PPTX
Automated testing of ASP .Net Core applications
PDF
How Testability Inspires AngularJS Design / Ran Mizrahi
PPTX
Integration Testing with Selenium
PDF
Agile Work Quality: Test Driven Development and Unit Tests
PDF
GraphQL-PHP: Dos and don'ts
PDF
Angular 2 observables
Testing your code
Unit Test your Views
Automated testing of ASP .Net Core applications
How Testability Inspires AngularJS Design / Ran Mizrahi
Integration Testing with Selenium
Agile Work Quality: Test Driven Development and Unit Tests
GraphQL-PHP: Dos and don'ts
Angular 2 observables

What's hot (20)

PPTX
Automate test, tools, advantages, and disadvantages
PPTX
JavaScript Metaprogramming with ES 2015 Proxy
PPTX
Principles and patterns for test driven development
PPTX
Intro to TDD and BDD
PPTX
Refactoring Legacy Web Forms for Test Automation
PPTX
Building large and scalable mission critical applications with React
PPTX
Setting Up CircleCI Workflows for Your Salesforce Apps
PDF
Agile2013 - Integration testing in enterprises using TaaS - via Case Study
PPTX
Testing - Is This Even a Thing?
PDF
Алексей Ященко и Ярослав Волощук "False simplicity of front-end applications"
PDF
Unit testing - A&BP CC
PDF
TestCorner #22 - How DevOps helps QA daily works​
 
PDF
Никита Галкин "Testing in Frontend World"
PDF
Putting Quality First through Continuous Testing
PDF
Testing in FrontEnd World by Nikita Galkin
PDF
JavaScript Fetch API
PDF
Unit Testing your React / Redux app (@BucharestJS)
PPTX
Karate for Complex Web-Service API Testing by Peter Thomas
PPTX
I am hooked on React
PPTX
Ntd2015_pt_kanban_ppt
Automate test, tools, advantages, and disadvantages
JavaScript Metaprogramming with ES 2015 Proxy
Principles and patterns for test driven development
Intro to TDD and BDD
Refactoring Legacy Web Forms for Test Automation
Building large and scalable mission critical applications with React
Setting Up CircleCI Workflows for Your Salesforce Apps
Agile2013 - Integration testing in enterprises using TaaS - via Case Study
Testing - Is This Even a Thing?
Алексей Ященко и Ярослав Волощук "False simplicity of front-end applications"
Unit testing - A&BP CC
TestCorner #22 - How DevOps helps QA daily works​
 
Никита Галкин "Testing in Frontend World"
Putting Quality First through Continuous Testing
Testing in FrontEnd World by Nikita Galkin
JavaScript Fetch API
Unit Testing your React / Redux app (@BucharestJS)
Karate for Complex Web-Service API Testing by Peter Thomas
I am hooked on React
Ntd2015_pt_kanban_ppt
Ad

Viewers also liked (20)

PPTX
Fast start tv b#1 p11_mvp_produto_minimo_viavel
PDF
3.formulario de agenda telefonica
PDF
Dr Heather Williams
DOC
CORLEE BOB LARENA
PDF
JavaScript
PPTX
Extra clase de religión
PPTX
Social Engineering and Identity Theft
PPTX
SLIDE FINAL PAPER PALEMBANG
PDF
Jakub Cimoradsky
PPT
Reittiluokitus of 2013 suomen latu
DOCX
PPTX
First class Testing
PPTX
Extra clase de religión4654
PPTX
Relatório agosto - Quem se Importa
PPT
Resolving conflicts
PPTX
Introduction to selenium web driver
PDF
Gps -paikantimen datan syöttäminen Garmin BaseCampiin
PPTX
Graphs of Log functions
DOC
PPTX
Aprendisaje en las materias durate el semestre
Fast start tv b#1 p11_mvp_produto_minimo_viavel
3.formulario de agenda telefonica
Dr Heather Williams
CORLEE BOB LARENA
JavaScript
Extra clase de religión
Social Engineering and Identity Theft
SLIDE FINAL PAPER PALEMBANG
Jakub Cimoradsky
Reittiluokitus of 2013 suomen latu
First class Testing
Extra clase de religión4654
Relatório agosto - Quem se Importa
Resolving conflicts
Introduction to selenium web driver
Gps -paikantimen datan syöttäminen Garmin BaseCampiin
Graphs of Log functions
Aprendisaje en las materias durate el semestre
Ad

Similar to Testing your code (20)

PPTX
JUNit Presentation
PPTX
TDD - Unit Testing
PPTX
Test-Driven Development
PDF
Android Test Driven Development & Android Unit Testing
PPTX
Write tests, please
ODP
Testing In Java
ODP
Testing In Java4278
PDF
May: Automated Developer Testing: Achievements and Challenges
PPTX
Presentation
PPTX
JUnit Test Case With Processminer modules.pptx
PDF
The Evolution of Development Testing
PDF
End to End Testing: Bug Squashing for API Developers
PPTX
SE2018_Lec 20_ Test-Driven Development (TDD)
PDF
Strategy-driven Test Generation with Open Source Frameworks
PPTX
Automation test
PPTX
JUnit 5 - from Lambda to Alpha and beyond
PPTX
Test-Driven Design Insights@DevoxxBE 2023.pptx
PPTX
unit 1 (1).pptx
PPTX
Test Driven Development - a Practitioner’s Perspective
PPTX
Testing Spring Applications
JUNit Presentation
TDD - Unit Testing
Test-Driven Development
Android Test Driven Development & Android Unit Testing
Write tests, please
Testing In Java
Testing In Java4278
May: Automated Developer Testing: Achievements and Challenges
Presentation
JUnit Test Case With Processminer modules.pptx
The Evolution of Development Testing
End to End Testing: Bug Squashing for API Developers
SE2018_Lec 20_ Test-Driven Development (TDD)
Strategy-driven Test Generation with Open Source Frameworks
Automation test
JUnit 5 - from Lambda to Alpha and beyond
Test-Driven Design Insights@DevoxxBE 2023.pptx
unit 1 (1).pptx
Test Driven Development - a Practitioner’s Perspective
Testing Spring Applications

More from Return on Intelligence (20)

PPTX
Clean Code Approach
PPTX
Code Coverage
PPTX
Effective Communication in english
PPTX
Anti-patterns
PPTX
Conflicts Resolving
PPTX
Database versioning with liquibase
PPTX
Effective Feedback
PPTX
English for Negotiations 2016
PPTX
Lean Software Development
PPT
Unit Tests? It is Very Simple and Easy!
PPTX
Quick Start to AngularJS
PPTX
Introduction to Backbone.js & Marionette.js
PPTX
Types of testing and their classification
PPTX
Introduction to EJB
PPTX
Enterprise Service Bus
PPTX
Apache cassandra - future without boundaries (part3)
PPTX
Apache cassandra - future without boundaries (part2)
PPTX
Apache cassandra - future without boundaries (part1)
PPTX
Career development in exigen services
PPTX
Enterprise service bus part 2
Clean Code Approach
Code Coverage
Effective Communication in english
Anti-patterns
Conflicts Resolving
Database versioning with liquibase
Effective Feedback
English for Negotiations 2016
Lean Software Development
Unit Tests? It is Very Simple and Easy!
Quick Start to AngularJS
Introduction to Backbone.js & Marionette.js
Types of testing and their classification
Introduction to EJB
Enterprise Service Bus
Apache cassandra - future without boundaries (part3)
Apache cassandra - future without boundaries (part2)
Apache cassandra - future without boundaries (part1)
Career development in exigen services
Enterprise service bus part 2

Recently uploaded (20)

PPTX
Why Generative AI is the Future of Content, Code & Creativity?
PDF
Product Update: Alluxio AI 3.7 Now with Sub-Millisecond Latency
PDF
Designing Intelligence for the Shop Floor.pdf
PPTX
Embracing Complexity in Serverless! GOTO Serverless Bengaluru
PDF
Digital Systems & Binary Numbers (comprehensive )
PDF
Nekopoi APK 2025 free lastest update
PDF
CCleaner Pro 6.38.11537 Crack Final Latest Version 2025
PPTX
Operating system designcfffgfgggggggvggggggggg
PDF
iTop VPN 6.5.0 Crack + License Key 2025 (Premium Version)
PDF
Download FL Studio Crack Latest version 2025 ?
PDF
How AI/LLM recommend to you ? GDG meetup 16 Aug by Fariman Guliev
PDF
Complete Guide to Website Development in Malaysia for SMEs
PDF
Design an Analysis of Algorithms II-SECS-1021-03
PDF
Cost to Outsource Software Development in 2025
PDF
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
PPTX
CHAPTER 2 - PM Management and IT Context
PDF
Website Design Services for Small Businesses.pdf
DOCX
Greta — No-Code AI for Building Full-Stack Web & Mobile Apps
PDF
Salesforce Agentforce AI Implementation.pdf
PDF
Wondershare Filmora 15 Crack With Activation Key [2025
Why Generative AI is the Future of Content, Code & Creativity?
Product Update: Alluxio AI 3.7 Now with Sub-Millisecond Latency
Designing Intelligence for the Shop Floor.pdf
Embracing Complexity in Serverless! GOTO Serverless Bengaluru
Digital Systems & Binary Numbers (comprehensive )
Nekopoi APK 2025 free lastest update
CCleaner Pro 6.38.11537 Crack Final Latest Version 2025
Operating system designcfffgfgggggggvggggggggg
iTop VPN 6.5.0 Crack + License Key 2025 (Premium Version)
Download FL Studio Crack Latest version 2025 ?
How AI/LLM recommend to you ? GDG meetup 16 Aug by Fariman Guliev
Complete Guide to Website Development in Malaysia for SMEs
Design an Analysis of Algorithms II-SECS-1021-03
Cost to Outsource Software Development in 2025
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
CHAPTER 2 - PM Management and IT Context
Website Design Services for Small Businesses.pdf
Greta — No-Code AI for Building Full-Stack Web & Mobile Apps
Salesforce Agentforce AI Implementation.pdf
Wondershare Filmora 15 Crack With Activation Key [2025

Testing your code