SlideShare a Scribd company logo
1 of 53
Download to read offline
How to keep normal blood
pressure using TDD
A little bit about me
● Java developer at PrivatBank
● more than 3 years of experience
● much less experience in TDD
● blog: kastordriver.one
● e-mail: KastorDriver@gmail.com
Agenda
● what is TDD?
● basic principles of technique
● how to write tests correctly
● tools from the arsenal of Java developer
● some code and examples
Pyramid of fate tests
Unit tests
Integration tests
Manual
tests
What is TDD?
● tests first
● it is not about testing
● it is about design
● and little about documentation
● but they do not replace architecture and
design
Pros
● better design, because you think before writing
● documentation that we can trust
● fast feedback (faster than QA and debug)
● refactoring is encouraged
● minimalistic code
Cons
● not suitable for GUI and database schema development
● discipline is required
● discipline is required for all team members
● erroneous test leads to the erroneous code (problem?)
Test firstTest last
Test last
● we concentrate on the parts of the code instead of design
● by the time of writing tests we get tired
● tests are being wrote taking into account rakes and crutches
● “test last” requires a powerful self-organization (only superhero
is able to do that)
Test first
● write tests on the first wave of enthusiasm
● incentive for write code - pass the test
● look at issue from the user's perspective
● the code is tested and is minimal
Three laws of TDD
● You must not write code while tests
are red
● You must not be farther than one
step from green line
● You must not write code more than
necessary for passing tests
How does it look?
● think before writing test
● formalize business requirements in tests
● name of test has to clearly describe the
purpose of the test
● check that the test fails
Note: Tests clarity should be more important than avoiding code duplication
RED
GREENREFACTOR
How does it look?
● write enough code to compile and pass
the test. No more
● check that the test is passed
● check all other tests
RED
REFACTOR GREEN
How does it look?
● get rid of duplication
● think about design
● go to “red” step
GREENREFACTOR
RED
Provide correct tests names
You should not:
● name test same as tested method
● name tests like: testSomeMethod1, testSomeMethod2...
Provide correct tests names
Name of test should:
● describe feature or specification
● describe purpose of test
● describe what object does, but not what it is
● When [Action] Then [Verification]
@Test
public void whenNumberIsNotMultipleOf3And5ThenReturnTheSameNumber() {
FizzBuzzGame fizzBuzz = new FizzBuzzGame();
assertEquals(“1”, fizzBuzz.fizzBuzzNumber(1));
}
public class FizzBuzzGame {
public String fizzBuzzNumber(int number) {
return String.valueOf(1);
}
}
@Test
public void whenNumberIsNotMultipleOf3And5ThenReturnTheSameNumber() {
FizzBuzzGame fizzBuzz = new FizzBuzzGame();
assertEquals(“1”, fizzBuzz.fizzBuzzNumber(1));
assertEquals(“2”, fizzBuzz.fizzBuzzNumber(2));
}
public class FizzBuzzGame {
public String fizzBuzzNumber(int number) {
return String.valueOf(number);
}
}
private FizzBuzzGame fizzBuzzGame;
@Before
public void setUp() throws Exception {
fizzBuzzGame = new FizzBuzzGame();
}
@Test
public void whenNumberIsNotMultipleOf3And5ThenReturnTheSameNumber() {
assertEquals("1", fizzBuzzGame.fizzBuzzNumber(1));
assertEquals("2", fizzBuzzGame.fizzBuzzNumber(2));
}
@Test
public void whenNumberIsMultipleOf3ThenReturnFizz() {
assertEquals("Fizz", fizzBuzzGame.fizzBuzzNumber(3));
assertEquals("Fizz", fizzBuzzGame.fizzBuzzNumber(9));
}
public class FizzBuzzGame {
public String fizzBuzzNumber(int number) {
if (number % 3 == 0) return "Fizz";
return String.valueOf(number);
}
}
private FizzBuzzGame fizzBuzzGame;
@Before
public void setUp() throws Exception {
fizzBuzzGame = new FizzBuzzGame();
}
@Test
public void whenNumberIsNotMultipleOf3And5ThenReturnTheSameNumber() {
assertEquals("1", fizzBuzzGame.fizzBuzzNumber(1));
assertEquals("2", fizzBuzzGame.fizzBuzzNumber(2));
}
@Test
public void whenNumberIsMultipleOf3ThenReturnFizz() {
assertEquals("Fizz", fizzBuzzGame.fizzBuzzNumber(3));
assertEquals("Fizz", fizzBuzzGame.fizzBuzzNumber(9));
}
@Test
public void whenNumberIsMultipleOf5ThenReturnBuzz() {
assertEquals("Buzz", fizzBuzzGame.fizzBuzzNumber(5));
assertEquals("Buzz", fizzBuzzGame.fizzBuzzNumber(10));
}
public class FizzBuzzGame {
public String fizzBuzzNumber(int number) {
if (number % 3 == 0) return "Fizz";
if (number % 5 == 0) return "Buzz";
return String.valueOf(number);
}
}
private FizzBuzzGame fizzBuzzGame;
@Before
public void setUp() throws Exception {
fizzBuzzGame = new FizzBuzzGame();
}
@Test
public void whenNumberIsNotMultipleOf3And5ThenReturnTheSameNumber() {
assertEquals("1", fizzBuzzGame.fizzBuzzNumber(1));
assertEquals("2", fizzBuzzGame.fizzBuzzNumber(2));
}
@Test
public void whenNumberIsMultipleOf3ThenReturnFizz() {
assertEquals("Fizz", fizzBuzzGame.fizzBuzzNumber(3));
assertEquals("Fizz", fizzBuzzGame.fizzBuzzNumber(9));
}
@Test
public void whenNumberIsMultipleOf5ThenReturnBazz() {
assertEquals("Bazz", fizzBuzzGame.fizzBuzzNumber(5));
assertEquals("Bazz", fizzBuzzGame.fizzBuzzNumber(10));
}
@Test
public void whenNumberIsMultipleOf3And5ThenReturnFizzBazz() {
assertEquals("FizzBazz", fizzBuzzGame.fizzBuzzNumber(15));
assertEquals("FizzBazz", fizzBuzzGame.fizzBuzzNumber(30));
}
public class FizzBuzzGame {
public String fizzBuzzNumber(int number) {
if (number % 3 == 0) return "Fizz";
if (number % 5 == 0) return "Bazz";
if (number % 3 == 0 && number % 5 == 0) return "FizzBazz";
return String.valueOf(number);
}
}
public class FizzBuzzGame {
public String fizzBuzzNumber(int number) {
if (number % 3 == 0) return "Fizz";
if (number % 5 == 0) return "Bazz";
if (number % 3 == 0 && number % 5 == 0) return "FizzBazz";
return String.valueOf(number);
}
}
org.junit.ComparisonFailure:
Expected :FizzBazz
Actual :Fizz
. . .
FizzBuzzTest.whenNumberIsMultipleOf3And5ThenReturnFizzBazz(FizzBuzzTest.java:36)
public class FizzBuzzGame {
public String fizzBuzzNumber(int number) {
if (number % 3 == 0 && number % 5 == 0) return "FizzBazz";
if (number % 3 == 0) return "Fizz";
if (number % 5 == 0) return "Bazz";
return String.valueOf(number);
}
}
private FizzBuzzGame fizzBuzzGame;
@Before
public void setUp() throws Exception {
fizzBuzzGame = new FizzBuzzGame();
}
@Test
public void whenNumberIsNotMultipleOf3And5ThenReturnTheSameNumber() {
assertEquals("1", fizzBuzzGame.fizzBuzzNumber(1));
assertEquals("2", fizzBuzzGame.fizzBuzzNumber(2));
}
@Test
public void whenNumberIsMultipleOnlyOf3ThenReturnFizz() {
assertEquals("Fizz", fizzBuzzGame.fizzBuzzNumber(3));
assertEquals("Fizz", fizzBuzzGame.fizzBuzzNumber(9));
}
@Test
public void whenNumberIsMultipleOnlyOf5ThenReturnBazz() {
assertEquals("Bazz", fizzBuzzGame.fizzBuzzNumber(5));
assertEquals("Bazz", fizzBuzzGame.fizzBuzzNumber(10));
}
@Test
public void whenNumberIsMultipleOf3And5ThenReturnFizzBazz() {
assertEquals("FizzBazz", fizzBuzzGame.fizzBuzzNumber(15));
assertEquals("FizzBazz", fizzBuzzGame.fizzBuzzNumber(30));
}
public class FizzBuzzGame {
public String fizzBuzzNumber(int number) {
StringBuilder result = new StringBuilder();
if (number % 3 == 0) {
result.append("Fizz");
}
if (number % 5 == 0) {
result.append("Bazz");
}
return result.length() == 0 ? String.valueOf(number)
: result.toString();
}
}
Separate and rule your tests
http://www.kastordriver.one/2017/02/separate-and-rule-your-tests.html
Unit tests
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.19</version>
<configuration>
<includes>
<include>**/*Test.java</include>
</includes>
</configuration>
</plugin>
Integration tests
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<version>2.19.1</version>
<configuration>
<includes>
<include>**/*IT.java</include>
</includes>
</configuration>
<executions>
<execution>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
</execution>
</executions>
</plugin>
We don't have time to write unit tests
Should I write code in a single
class with hundreds methods
without other classes, design
patterns and so on? No? But I
do not have time for that!
http://www.yegor256.com/2015/07/16/fools-dont-write-unit-tests.html
Are You Still Debugging?
Unit testing is a technique that
completely replaces
debugging. If debugging is
required, the design is not
good enough.
http://www.yegor256.com/2016/02/09/are-you-still-debugging.html
Legacy code
Legacy code
● write tests for legacy code
● rename, extract method, extract
interface
● write tests again
● sorry, but no fun
● Mockito makes mocking very easy
● It is extremely easy to read mock code
● Mockito works in any environment and has no
external dependencies
Sip of mockito
import static org.mockito.Mockito.*;
// mock creation
List mockedList = mock(List.class);
// using mock object - it does not throw any "unexpected interaction" exception
mockedList.add("one");
mockedList.add("one");
mockedList.clear();
// selective, explicit, highly readable verification
verify(mockedList, times(2)).add("one");
verify(mockedList).clear();
You can verify interactions
@Test(expected = RuntimeException.class)
public void test() throws Exception {
// you can mock concrete classes, not only interfaces
LinkedList mockedList = mock(LinkedList.class);
// stubbing appears before the actual execution
when(mockedList.get(0)).thenReturn("first");
when(mockedList.get(1)).thenThrow(new RuntimeException());
// the following prints "null" because get(999) was not stubbed
assertNull(mockedList.get(999));
assertEquals("first", mockedList.get(0));
//throw RuntimeException
mockedList.get(1);
}
You can stub method calls
Be careful with mocks
● Don't mock type you don't own!
● Don't mock everything, it's an anti-pattern
● Don't mock value objects
Mockito discourages
● Can I mock static methods?
○ No. Mockito prefers object orientation
and dependency injection over static,
procedural code that is hard to
understand and change.
● Can I mock private methods?
○ No. From the standpoint of testing...
private methods don't exist.
● Supports Mockito-style mocking.
● Mocks constructors, static, private and final
methods.
Powermock
class FileUtils {
public static Set<String> readUniqueWords(String path) throws IOException {
String text = new String(Files.readAllBytes(Paths.get(path)), "UTF-8");
Set<String> words = new HashSet<>();
for (String word : text.split(" ")) {
words.add(word);
}
return words;
}
}
@RunWith(PowerMockRunner.class)
@PrepareForTest({Files.class, FileUtils.class})
public class FileUtilsTest {
@Test
public void readUniqueWordsMustReturnOnlyUniqueWords() throws Exception {
final String somePath = "somePath";
Path fakePath = Paths.get(somePath);
PowerMockito.mockStatic(Files.class);
when(Files.readAllBytes(fakePath)).thenReturn("One two two three".getBytes());
Set<String> result = FileUtils.readUniqueWords(somePath);
assertEquals(3, result.size());
assertTrue(result.contains("One"));
assertTrue(result.contains("two"));
assertTrue(result.contains("three"));
}
}
class Text {
private final String path;
Text(String src) {
this.path = src;
}
public String readText() throws IOException {
return new String(Files.readAllBytes(Paths.get(this.path)), "UTF-8");
}
}
public class UniqueWords {
private final String text;
UniqueWords(String txt) {
this.text = txt;
}
public Set<String> readUniqueWords() {
Set<String> words = new HashSet<>();
for (String word : this.text.split(" ")) {
words.add(word);
}
return words;
}
}
public class UniqueWordsTest {
@Test
public void readUniqueWordsMustReturnOnlyUniqueWords() throws Exception {
Set<String> result = new UniqueWords("One two two three")
.readUniqueWords();
assertEquals(3, result.size());
assertTrue(result.contains("One"));
assertTrue(result.contains("two"));
assertTrue(result.contains("three"));
}
}
Odd man out
Cobertura maven plugin allows you:
● Check the coverage percentages for unit
tests and integration tests
● fail the build if the targets are not met
Keep a code coverage on a radar
http://www.kastordriver.one/2017/02/keep-code-coverage-on-radar.html
Useful links
Kent Beck "Test Driven Development"
Андрей Солнцев “Пацан накодил - пацан протестил!
Mockito wiki
Николай Алименков "Сага о том, как Java-
разработчики должны тестировать свои
приложения"
Victor Farcic, Alex Garcia "Test-Driven Java Development"
Thank you for your attention

More Related Content

What's hot

TDD CrashCourse Part3: TDD Techniques
TDD CrashCourse Part3: TDD TechniquesTDD CrashCourse Part3: TDD Techniques
TDD CrashCourse Part3: TDD TechniquesDavid Rodenas
 
Unit Test Your Database
Unit Test Your DatabaseUnit Test Your Database
Unit Test Your DatabaseDavid Wheeler
 
Developer Test - Things to Know
Developer Test - Things to KnowDeveloper Test - Things to Know
Developer Test - Things to Knowvilniusjug
 
Google mock for dummies
Google mock for dummiesGoogle mock for dummies
Google mock for dummiesHarry Potter
 
JAVASCRIPT Test Driven Development & Jasmine
JAVASCRIPT Test Driven Development & JasmineJAVASCRIPT Test Driven Development & Jasmine
JAVASCRIPT Test Driven Development & JasmineAnup Singh
 
20111018 boost and gtest
20111018 boost and gtest20111018 boost and gtest
20111018 boost and gtestWill Shen
 
Presentation_C++UnitTest
Presentation_C++UnitTestPresentation_C++UnitTest
Presentation_C++UnitTestRaihan Masud
 
Testing, Learning and Professionalism — 20171214
Testing, Learning and Professionalism — 20171214Testing, Learning and Professionalism — 20171214
Testing, Learning and Professionalism — 20171214David Rodenas
 
Automated testing in Python and beyond
Automated testing in Python and beyondAutomated testing in Python and beyond
Automated testing in Python and beyonddn
 
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
 
Testers guide to unit testing
Testers guide to unit testingTesters guide to unit testing
Testers guide to unit testingCraig Risi
 
ES3-2020-P2 Bowling Game Kata
ES3-2020-P2 Bowling Game KataES3-2020-P2 Bowling Game Kata
ES3-2020-P2 Bowling Game KataDavid Rodenas
 
JAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
JAVASCRIPT TDD(Test driven Development) & Qunit TutorialJAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
JAVASCRIPT TDD(Test driven Development) & Qunit TutorialAnup Singh
 
TDD in Python With Pytest
TDD in Python With PytestTDD in Python With Pytest
TDD in Python With PytestEddy Reyes
 

What's hot (20)

TDD CrashCourse Part3: TDD Techniques
TDD CrashCourse Part3: TDD TechniquesTDD CrashCourse Part3: TDD Techniques
TDD CrashCourse Part3: TDD Techniques
 
Unit Test Your Database
Unit Test Your DatabaseUnit Test Your Database
Unit Test Your Database
 
Developer Test - Things to Know
Developer Test - Things to KnowDeveloper Test - Things to Know
Developer Test - Things to Know
 
Google mock for dummies
Google mock for dummiesGoogle mock for dummies
Google mock for dummies
 
Cursus phpunit
Cursus phpunitCursus phpunit
Cursus phpunit
 
JAVASCRIPT Test Driven Development & Jasmine
JAVASCRIPT Test Driven Development & JasmineJAVASCRIPT Test Driven Development & Jasmine
JAVASCRIPT Test Driven Development & Jasmine
 
20111018 boost and gtest
20111018 boost and gtest20111018 boost and gtest
20111018 boost and gtest
 
Auto testing!
Auto testing!Auto testing!
Auto testing!
 
Presentation_C++UnitTest
Presentation_C++UnitTestPresentation_C++UnitTest
Presentation_C++UnitTest
 
Refactoring
RefactoringRefactoring
Refactoring
 
Testing, Learning and Professionalism — 20171214
Testing, Learning and Professionalism — 20171214Testing, Learning and Professionalism — 20171214
Testing, Learning and Professionalism — 20171214
 
Testacular
TestacularTestacular
Testacular
 
Automated testing in Python and beyond
Automated testing in Python and beyondAutomated testing in Python and beyond
Automated testing in Python and beyond
 
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
 
Testers guide to unit testing
Testers guide to unit testingTesters guide to unit testing
Testers guide to unit testing
 
ES3-2020-05 Testing
ES3-2020-05 TestingES3-2020-05 Testing
ES3-2020-05 Testing
 
ES3-2020-P2 Bowling Game Kata
ES3-2020-P2 Bowling Game KataES3-2020-P2 Bowling Game Kata
ES3-2020-P2 Bowling Game Kata
 
JAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
JAVASCRIPT TDD(Test driven Development) & Qunit TutorialJAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
JAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
 
Presentation Unit Testing process
Presentation Unit Testing processPresentation Unit Testing process
Presentation Unit Testing process
 
TDD in Python With Pytest
TDD in Python With PytestTDD in Python With Pytest
TDD in Python With Pytest
 

Similar to "How keep normal blood pressure using TDD" By Roman Loparev

Tdd is not about testing (OOP)
Tdd is not about testing (OOP)Tdd is not about testing (OOP)
Tdd is not about testing (OOP)Gianluca Padovani
 
North Virginia Coldfusion User Group Meetup - Testbox - July 19th 2017
North Virginia Coldfusion User Group Meetup - Testbox - July 19th 2017North Virginia Coldfusion User Group Meetup - Testbox - July 19th 2017
North Virginia Coldfusion User Group Meetup - Testbox - July 19th 2017Ortus Solutions, Corp
 
Tdd is not about testing (C++ version)
Tdd is not about testing (C++ version)Tdd is not about testing (C++ version)
Tdd is not about testing (C++ version)Gianluca Padovani
 
Developer Tests - Things to Know
Developer Tests - Things to KnowDeveloper Tests - Things to Know
Developer Tests - Things to KnowVaidas Pilkauskas
 
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
 
ITB2016 -BDD testing and automation from the trenches
ITB2016 -BDD testing and automation from the trenchesITB2016 -BDD testing and automation from the trenches
ITB2016 -BDD testing and automation from the trenchesOrtus Solutions, Corp
 
Building unit tests correctly with visual studio 2013
Building unit tests correctly with visual studio 2013Building unit tests correctly with visual studio 2013
Building unit tests correctly with visual studio 2013Dror Helper
 
3 Ways to test your ColdFusion API - 2017 Adobe CF Summit
3 Ways to test your ColdFusion API - 2017 Adobe CF Summit3 Ways to test your ColdFusion API - 2017 Adobe CF Summit
3 Ways to test your ColdFusion API - 2017 Adobe CF SummitOrtus Solutions, Corp
 
2016 10-04: tdd++: tdd made easier
2016 10-04: tdd++: tdd made easier2016 10-04: tdd++: tdd made easier
2016 10-04: tdd++: tdd made easierChristian Hujer
 
3 WAYS TO TEST YOUR COLDFUSION API -
3 WAYS TO TEST YOUR COLDFUSION API - 3 WAYS TO TEST YOUR COLDFUSION API -
3 WAYS TO TEST YOUR COLDFUSION API - Ortus Solutions, Corp
 
3 WAYS TO TEST YOUR COLDFUSION API
3 WAYS TO TEST YOUR COLDFUSION API3 WAYS TO TEST YOUR COLDFUSION API
3 WAYS TO TEST YOUR COLDFUSION APIGavin Pickin
 
Grails unit testing
Grails unit testingGrails unit testing
Grails unit testingpleeps
 
Intro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiIntro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiRan Mizrahi
 
Shift-Left Testing: QA in a DevOps World by David Laulusa
Shift-Left Testing: QA in a DevOps World by David LaulusaShift-Left Testing: QA in a DevOps World by David Laulusa
Shift-Left Testing: QA in a DevOps World by David LaulusaQA or the Highway
 

Similar to "How keep normal blood pressure using TDD" By Roman Loparev (20)

Tdd is not about testing (OOP)
Tdd is not about testing (OOP)Tdd is not about testing (OOP)
Tdd is not about testing (OOP)
 
North Virginia Coldfusion User Group Meetup - Testbox - July 19th 2017
North Virginia Coldfusion User Group Meetup - Testbox - July 19th 2017North Virginia Coldfusion User Group Meetup - Testbox - July 19th 2017
North Virginia Coldfusion User Group Meetup - Testbox - July 19th 2017
 
Tdd is not about testing (C++ version)
Tdd is not about testing (C++ version)Tdd is not about testing (C++ version)
Tdd is not about testing (C++ version)
 
Unit testing
Unit testingUnit testing
Unit testing
 
Developer Tests - Things to Know
Developer Tests - Things to KnowDeveloper Tests - Things to Know
Developer Tests - Things to Know
 
TDD Best Practices
TDD Best PracticesTDD Best Practices
TDD Best Practices
 
TDD reloaded - JUGTAA 24 Ottobre 2012
TDD reloaded - JUGTAA 24 Ottobre 2012TDD reloaded - JUGTAA 24 Ottobre 2012
TDD reloaded - JUGTAA 24 Ottobre 2012
 
ITB2016 -BDD testing and automation from the trenches
ITB2016 -BDD testing and automation from the trenchesITB2016 -BDD testing and automation from the trenches
ITB2016 -BDD testing and automation from the trenches
 
Building unit tests correctly with visual studio 2013
Building unit tests correctly with visual studio 2013Building unit tests correctly with visual studio 2013
Building unit tests correctly with visual studio 2013
 
3 Ways to test your ColdFusion API - 2017 Adobe CF Summit
3 Ways to test your ColdFusion API - 2017 Adobe CF Summit3 Ways to test your ColdFusion API - 2017 Adobe CF Summit
3 Ways to test your ColdFusion API - 2017 Adobe CF Summit
 
2016 10-04: tdd++: tdd made easier
2016 10-04: tdd++: tdd made easier2016 10-04: tdd++: tdd made easier
2016 10-04: tdd++: tdd made easier
 
3 WAYS TO TEST YOUR COLDFUSION API -
3 WAYS TO TEST YOUR COLDFUSION API - 3 WAYS TO TEST YOUR COLDFUSION API -
3 WAYS TO TEST YOUR COLDFUSION API -
 
3 WAYS TO TEST YOUR COLDFUSION API
3 WAYS TO TEST YOUR COLDFUSION API3 WAYS TO TEST YOUR COLDFUSION API
3 WAYS TO TEST YOUR COLDFUSION API
 
Grails unit testing
Grails unit testingGrails unit testing
Grails unit testing
 
Testing Spring Applications
Testing Spring ApplicationsTesting Spring Applications
Testing Spring Applications
 
Test Driven
Test DrivenTest Driven
Test Driven
 
Intro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiIntro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran Mizrahi
 
Golang dot-testing-lite
Golang dot-testing-liteGolang dot-testing-lite
Golang dot-testing-lite
 
Unit testing on mobile apps
Unit testing on mobile appsUnit testing on mobile apps
Unit testing on mobile apps
 
Shift-Left Testing: QA in a DevOps World by David Laulusa
Shift-Left Testing: QA in a DevOps World by David LaulusaShift-Left Testing: QA in a DevOps World by David Laulusa
Shift-Left Testing: QA in a DevOps World by David Laulusa
 

More from Ciklum Ukraine

"Through the three circles of the it hell" by Roman Liashenko
"Through the three circles of the it hell" by Roman Liashenko"Through the three circles of the it hell" by Roman Liashenko
"Through the three circles of the it hell" by Roman LiashenkoCiklum Ukraine
 
Alex Pazhyn: Google_Material_Design
Alex Pazhyn: Google_Material_DesignAlex Pazhyn: Google_Material_Design
Alex Pazhyn: Google_Material_DesignCiklum Ukraine
 
Introduction to amazon web services for developers
Introduction to amazon web services for developersIntroduction to amazon web services for developers
Introduction to amazon web services for developersCiklum Ukraine
 
Your 1st Apple watch Application
Your 1st Apple watch ApplicationYour 1st Apple watch Application
Your 1st Apple watch ApplicationCiklum Ukraine
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven DevelopmentCiklum Ukraine
 
Back to the future: ux trends 2015
Back to the future: ux trends 2015Back to the future: ux trends 2015
Back to the future: ux trends 2015Ciklum Ukraine
 
Developing high load systems using C++
Developing high load systems using C++Developing high load systems using C++
Developing high load systems using C++Ciklum Ukraine
 
Collection view layout
Collection view layoutCollection view layout
Collection view layoutCiklum Ukraine
 
Introduction to auto layout
Introduction to auto layoutIntroduction to auto layout
Introduction to auto layoutCiklum Ukraine
 
Unit Testing: Special Cases
Unit Testing: Special CasesUnit Testing: Special Cases
Unit Testing: Special CasesCiklum Ukraine
 
Model-View-Controller: Tips&Tricks
Model-View-Controller: Tips&TricksModel-View-Controller: Tips&Tricks
Model-View-Controller: Tips&TricksCiklum Ukraine
 
Future of Outsourcing report published in The Times featuring Ciklum's CEO To...
Future of Outsourcing report published in The Times featuring Ciklum's CEO To...Future of Outsourcing report published in The Times featuring Ciklum's CEO To...
Future of Outsourcing report published in The Times featuring Ciklum's CEO To...Ciklum Ukraine
 
Михаил Попчук "Cкрытые резервы команд или 1+1=3"
Михаил Попчук "Cкрытые резервы команд или 1+1=3"Михаил Попчук "Cкрытые резервы команд или 1+1=3"
Михаил Попчук "Cкрытые резервы команд или 1+1=3"Ciklum Ukraine
 
"To be, rather than to seem” interview with Ciklum VP of HR Marina Vyshegorod...
"To be, rather than to seem” interview with Ciklum VP of HR Marina Vyshegorod..."To be, rather than to seem” interview with Ciklum VP of HR Marina Vyshegorod...
"To be, rather than to seem” interview with Ciklum VP of HR Marina Vyshegorod...Ciklum Ukraine
 

More from Ciklum Ukraine (20)

"Through the three circles of the it hell" by Roman Liashenko
"Through the three circles of the it hell" by Roman Liashenko"Through the three circles of the it hell" by Roman Liashenko
"Through the three circles of the it hell" by Roman Liashenko
 
Alex Pazhyn: Google_Material_Design
Alex Pazhyn: Google_Material_DesignAlex Pazhyn: Google_Material_Design
Alex Pazhyn: Google_Material_Design
 
Introduction to amazon web services for developers
Introduction to amazon web services for developersIntroduction to amazon web services for developers
Introduction to amazon web services for developers
 
Your 1st Apple watch Application
Your 1st Apple watch ApplicationYour 1st Apple watch Application
Your 1st Apple watch Application
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Back to the future: ux trends 2015
Back to the future: ux trends 2015Back to the future: ux trends 2015
Back to the future: ux trends 2015
 
Developing high load systems using C++
Developing high load systems using C++Developing high load systems using C++
Developing high load systems using C++
 
Collection view layout
Collection view layoutCollection view layout
Collection view layout
 
Introduction to auto layout
Introduction to auto layoutIntroduction to auto layout
Introduction to auto layout
 
Groovy on Android
Groovy on AndroidGroovy on Android
Groovy on Android
 
Unit Testing: Special Cases
Unit Testing: Special CasesUnit Testing: Special Cases
Unit Testing: Special Cases
 
Material design
Material designMaterial design
Material design
 
Kanban development
Kanban developmentKanban development
Kanban development
 
Mobile sketching
Mobile sketching Mobile sketching
Mobile sketching
 
More UX in our life
More UX in our lifeMore UX in our life
More UX in our life
 
Model-View-Controller: Tips&Tricks
Model-View-Controller: Tips&TricksModel-View-Controller: Tips&Tricks
Model-View-Controller: Tips&Tricks
 
Unit Tesing in iOS
Unit Tesing in iOSUnit Tesing in iOS
Unit Tesing in iOS
 
Future of Outsourcing report published in The Times featuring Ciklum's CEO To...
Future of Outsourcing report published in The Times featuring Ciklum's CEO To...Future of Outsourcing report published in The Times featuring Ciklum's CEO To...
Future of Outsourcing report published in The Times featuring Ciklum's CEO To...
 
Михаил Попчук "Cкрытые резервы команд или 1+1=3"
Михаил Попчук "Cкрытые резервы команд или 1+1=3"Михаил Попчук "Cкрытые резервы команд или 1+1=3"
Михаил Попчук "Cкрытые резервы команд или 1+1=3"
 
"To be, rather than to seem” interview with Ciklum VP of HR Marina Vyshegorod...
"To be, rather than to seem” interview with Ciklum VP of HR Marina Vyshegorod..."To be, rather than to seem” interview with Ciklum VP of HR Marina Vyshegorod...
"To be, rather than to seem” interview with Ciklum VP of HR Marina Vyshegorod...
 

Recently uploaded

Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesZilliz
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 

Recently uploaded (20)

Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector Databases
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 

"How keep normal blood pressure using TDD" By Roman Loparev

  • 1. How to keep normal blood pressure using TDD
  • 2. A little bit about me ● Java developer at PrivatBank ● more than 3 years of experience ● much less experience in TDD ● blog: kastordriver.one ● e-mail: KastorDriver@gmail.com
  • 3. Agenda ● what is TDD? ● basic principles of technique ● how to write tests correctly ● tools from the arsenal of Java developer ● some code and examples
  • 4. Pyramid of fate tests Unit tests Integration tests Manual tests
  • 5. What is TDD? ● tests first ● it is not about testing ● it is about design ● and little about documentation ● but they do not replace architecture and design
  • 6. Pros ● better design, because you think before writing ● documentation that we can trust ● fast feedback (faster than QA and debug) ● refactoring is encouraged ● minimalistic code
  • 7. Cons ● not suitable for GUI and database schema development ● discipline is required ● discipline is required for all team members ● erroneous test leads to the erroneous code (problem?)
  • 9. Test last ● we concentrate on the parts of the code instead of design ● by the time of writing tests we get tired ● tests are being wrote taking into account rakes and crutches ● “test last” requires a powerful self-organization (only superhero is able to do that)
  • 10. Test first ● write tests on the first wave of enthusiasm ● incentive for write code - pass the test ● look at issue from the user's perspective ● the code is tested and is minimal
  • 11. Three laws of TDD ● You must not write code while tests are red ● You must not be farther than one step from green line ● You must not write code more than necessary for passing tests
  • 12. How does it look? ● think before writing test ● formalize business requirements in tests ● name of test has to clearly describe the purpose of the test ● check that the test fails Note: Tests clarity should be more important than avoiding code duplication RED GREENREFACTOR
  • 13. How does it look? ● write enough code to compile and pass the test. No more ● check that the test is passed ● check all other tests RED REFACTOR GREEN
  • 14. How does it look? ● get rid of duplication ● think about design ● go to “red” step GREENREFACTOR RED
  • 15. Provide correct tests names You should not: ● name test same as tested method ● name tests like: testSomeMethod1, testSomeMethod2...
  • 16. Provide correct tests names Name of test should: ● describe feature or specification ● describe purpose of test ● describe what object does, but not what it is ● When [Action] Then [Verification]
  • 17.
  • 18. @Test public void whenNumberIsNotMultipleOf3And5ThenReturnTheSameNumber() { FizzBuzzGame fizzBuzz = new FizzBuzzGame(); assertEquals(“1”, fizzBuzz.fizzBuzzNumber(1)); }
  • 19. public class FizzBuzzGame { public String fizzBuzzNumber(int number) { return String.valueOf(1); } }
  • 20. @Test public void whenNumberIsNotMultipleOf3And5ThenReturnTheSameNumber() { FizzBuzzGame fizzBuzz = new FizzBuzzGame(); assertEquals(“1”, fizzBuzz.fizzBuzzNumber(1)); assertEquals(“2”, fizzBuzz.fizzBuzzNumber(2)); }
  • 21. public class FizzBuzzGame { public String fizzBuzzNumber(int number) { return String.valueOf(number); } }
  • 22. private FizzBuzzGame fizzBuzzGame; @Before public void setUp() throws Exception { fizzBuzzGame = new FizzBuzzGame(); } @Test public void whenNumberIsNotMultipleOf3And5ThenReturnTheSameNumber() { assertEquals("1", fizzBuzzGame.fizzBuzzNumber(1)); assertEquals("2", fizzBuzzGame.fizzBuzzNumber(2)); } @Test public void whenNumberIsMultipleOf3ThenReturnFizz() { assertEquals("Fizz", fizzBuzzGame.fizzBuzzNumber(3)); assertEquals("Fizz", fizzBuzzGame.fizzBuzzNumber(9)); }
  • 23. public class FizzBuzzGame { public String fizzBuzzNumber(int number) { if (number % 3 == 0) return "Fizz"; return String.valueOf(number); } }
  • 24. private FizzBuzzGame fizzBuzzGame; @Before public void setUp() throws Exception { fizzBuzzGame = new FizzBuzzGame(); } @Test public void whenNumberIsNotMultipleOf3And5ThenReturnTheSameNumber() { assertEquals("1", fizzBuzzGame.fizzBuzzNumber(1)); assertEquals("2", fizzBuzzGame.fizzBuzzNumber(2)); } @Test public void whenNumberIsMultipleOf3ThenReturnFizz() { assertEquals("Fizz", fizzBuzzGame.fizzBuzzNumber(3)); assertEquals("Fizz", fizzBuzzGame.fizzBuzzNumber(9)); } @Test public void whenNumberIsMultipleOf5ThenReturnBuzz() { assertEquals("Buzz", fizzBuzzGame.fizzBuzzNumber(5)); assertEquals("Buzz", fizzBuzzGame.fizzBuzzNumber(10)); }
  • 25. public class FizzBuzzGame { public String fizzBuzzNumber(int number) { if (number % 3 == 0) return "Fizz"; if (number % 5 == 0) return "Buzz"; return String.valueOf(number); } }
  • 26. private FizzBuzzGame fizzBuzzGame; @Before public void setUp() throws Exception { fizzBuzzGame = new FizzBuzzGame(); } @Test public void whenNumberIsNotMultipleOf3And5ThenReturnTheSameNumber() { assertEquals("1", fizzBuzzGame.fizzBuzzNumber(1)); assertEquals("2", fizzBuzzGame.fizzBuzzNumber(2)); } @Test public void whenNumberIsMultipleOf3ThenReturnFizz() { assertEquals("Fizz", fizzBuzzGame.fizzBuzzNumber(3)); assertEquals("Fizz", fizzBuzzGame.fizzBuzzNumber(9)); } @Test public void whenNumberIsMultipleOf5ThenReturnBazz() { assertEquals("Bazz", fizzBuzzGame.fizzBuzzNumber(5)); assertEquals("Bazz", fizzBuzzGame.fizzBuzzNumber(10)); } @Test public void whenNumberIsMultipleOf3And5ThenReturnFizzBazz() { assertEquals("FizzBazz", fizzBuzzGame.fizzBuzzNumber(15)); assertEquals("FizzBazz", fizzBuzzGame.fizzBuzzNumber(30)); }
  • 27. public class FizzBuzzGame { public String fizzBuzzNumber(int number) { if (number % 3 == 0) return "Fizz"; if (number % 5 == 0) return "Bazz"; if (number % 3 == 0 && number % 5 == 0) return "FizzBazz"; return String.valueOf(number); } }
  • 28. public class FizzBuzzGame { public String fizzBuzzNumber(int number) { if (number % 3 == 0) return "Fizz"; if (number % 5 == 0) return "Bazz"; if (number % 3 == 0 && number % 5 == 0) return "FizzBazz"; return String.valueOf(number); } } org.junit.ComparisonFailure: Expected :FizzBazz Actual :Fizz . . . FizzBuzzTest.whenNumberIsMultipleOf3And5ThenReturnFizzBazz(FizzBuzzTest.java:36)
  • 29. public class FizzBuzzGame { public String fizzBuzzNumber(int number) { if (number % 3 == 0 && number % 5 == 0) return "FizzBazz"; if (number % 3 == 0) return "Fizz"; if (number % 5 == 0) return "Bazz"; return String.valueOf(number); } }
  • 30. private FizzBuzzGame fizzBuzzGame; @Before public void setUp() throws Exception { fizzBuzzGame = new FizzBuzzGame(); } @Test public void whenNumberIsNotMultipleOf3And5ThenReturnTheSameNumber() { assertEquals("1", fizzBuzzGame.fizzBuzzNumber(1)); assertEquals("2", fizzBuzzGame.fizzBuzzNumber(2)); } @Test public void whenNumberIsMultipleOnlyOf3ThenReturnFizz() { assertEquals("Fizz", fizzBuzzGame.fizzBuzzNumber(3)); assertEquals("Fizz", fizzBuzzGame.fizzBuzzNumber(9)); } @Test public void whenNumberIsMultipleOnlyOf5ThenReturnBazz() { assertEquals("Bazz", fizzBuzzGame.fizzBuzzNumber(5)); assertEquals("Bazz", fizzBuzzGame.fizzBuzzNumber(10)); } @Test public void whenNumberIsMultipleOf3And5ThenReturnFizzBazz() { assertEquals("FizzBazz", fizzBuzzGame.fizzBuzzNumber(15)); assertEquals("FizzBazz", fizzBuzzGame.fizzBuzzNumber(30)); }
  • 31. public class FizzBuzzGame { public String fizzBuzzNumber(int number) { StringBuilder result = new StringBuilder(); if (number % 3 == 0) { result.append("Fizz"); } if (number % 5 == 0) { result.append("Bazz"); } return result.length() == 0 ? String.valueOf(number) : result.toString(); } }
  • 32. Separate and rule your tests http://www.kastordriver.one/2017/02/separate-and-rule-your-tests.html
  • 35. We don't have time to write unit tests Should I write code in a single class with hundreds methods without other classes, design patterns and so on? No? But I do not have time for that! http://www.yegor256.com/2015/07/16/fools-dont-write-unit-tests.html
  • 36. Are You Still Debugging? Unit testing is a technique that completely replaces debugging. If debugging is required, the design is not good enough. http://www.yegor256.com/2016/02/09/are-you-still-debugging.html
  • 38. Legacy code ● write tests for legacy code ● rename, extract method, extract interface ● write tests again ● sorry, but no fun
  • 39. ● Mockito makes mocking very easy ● It is extremely easy to read mock code ● Mockito works in any environment and has no external dependencies Sip of mockito
  • 40. import static org.mockito.Mockito.*; // mock creation List mockedList = mock(List.class); // using mock object - it does not throw any "unexpected interaction" exception mockedList.add("one"); mockedList.add("one"); mockedList.clear(); // selective, explicit, highly readable verification verify(mockedList, times(2)).add("one"); verify(mockedList).clear(); You can verify interactions
  • 41. @Test(expected = RuntimeException.class) public void test() throws Exception { // you can mock concrete classes, not only interfaces LinkedList mockedList = mock(LinkedList.class); // stubbing appears before the actual execution when(mockedList.get(0)).thenReturn("first"); when(mockedList.get(1)).thenThrow(new RuntimeException()); // the following prints "null" because get(999) was not stubbed assertNull(mockedList.get(999)); assertEquals("first", mockedList.get(0)); //throw RuntimeException mockedList.get(1); } You can stub method calls
  • 42. Be careful with mocks ● Don't mock type you don't own! ● Don't mock everything, it's an anti-pattern ● Don't mock value objects
  • 43. Mockito discourages ● Can I mock static methods? ○ No. Mockito prefers object orientation and dependency injection over static, procedural code that is hard to understand and change. ● Can I mock private methods? ○ No. From the standpoint of testing... private methods don't exist.
  • 44. ● Supports Mockito-style mocking. ● Mocks constructors, static, private and final methods. Powermock
  • 45. class FileUtils { public static Set<String> readUniqueWords(String path) throws IOException { String text = new String(Files.readAllBytes(Paths.get(path)), "UTF-8"); Set<String> words = new HashSet<>(); for (String word : text.split(" ")) { words.add(word); } return words; } }
  • 46. @RunWith(PowerMockRunner.class) @PrepareForTest({Files.class, FileUtils.class}) public class FileUtilsTest { @Test public void readUniqueWordsMustReturnOnlyUniqueWords() throws Exception { final String somePath = "somePath"; Path fakePath = Paths.get(somePath); PowerMockito.mockStatic(Files.class); when(Files.readAllBytes(fakePath)).thenReturn("One two two three".getBytes()); Set<String> result = FileUtils.readUniqueWords(somePath); assertEquals(3, result.size()); assertTrue(result.contains("One")); assertTrue(result.contains("two")); assertTrue(result.contains("three")); } }
  • 47. class Text { private final String path; Text(String src) { this.path = src; } public String readText() throws IOException { return new String(Files.readAllBytes(Paths.get(this.path)), "UTF-8"); } }
  • 48. public class UniqueWords { private final String text; UniqueWords(String txt) { this.text = txt; } public Set<String> readUniqueWords() { Set<String> words = new HashSet<>(); for (String word : this.text.split(" ")) { words.add(word); } return words; } }
  • 49. public class UniqueWordsTest { @Test public void readUniqueWordsMustReturnOnlyUniqueWords() throws Exception { Set<String> result = new UniqueWords("One two two three") .readUniqueWords(); assertEquals(3, result.size()); assertTrue(result.contains("One")); assertTrue(result.contains("two")); assertTrue(result.contains("three")); } }
  • 51. Cobertura maven plugin allows you: ● Check the coverage percentages for unit tests and integration tests ● fail the build if the targets are not met Keep a code coverage on a radar http://www.kastordriver.one/2017/02/keep-code-coverage-on-radar.html
  • 52. Useful links Kent Beck "Test Driven Development" Андрей Солнцев “Пацан накодил - пацан протестил! Mockito wiki Николай Алименков "Сага о том, как Java- разработчики должны тестировать свои приложения" Victor Farcic, Alex Garcia "Test-Driven Java Development"
  • 53. Thank you for your attention