SlideShare a Scribd company logo
www.luxoft.com
Test Driven Development
Using Mockito
By Andriy Slobodyanyk
www.luxoft.com
About me
Andriy Slobodyanyk
 Some years in Java Development
 Even TechLead of Luxoft team
 Bench press max 118 kg
www.luxoft.com
TDD
www.luxoft.com
TDD
 Tests
 Refactoring
 Documentation
 Design
www.luxoft.com
Interview Question
 There is a list of persons
 Select women and children from it
www.luxoft.com
Predicate
public List<Person> getVips(List<Person> persons) {
List<Person> result = new ArrayList<Person>();
for (Person p : persons) {
if (p.getGender() == FEMALE && p.getAge() > 16) {
result.add(p);
}
}
return result;
}
www.luxoft.com
TDD
If hard to write the test
then code design is bad
www.luxoft.com
Code “evolution”
@Service
public class PersonServiceImpl implements PersonService {
@Autowired
private UserRepository userRepository;
@Override
public void save(Person person) {
PersonEntity entity = new PersonEntity();
entity.setName(person.getName());
userRepository.save(entity);
}
}
www.luxoft.com
Code “evolution”
@Service
public class PersonServiceImpl implements PersonService {
@Autowired
private UserRepository userRepository;
@Autowired
private DeptRepository deptRepo;
@Override
public void save(Person person) {
PersonEntity entity = new PersonEntity();
entity.setName(person.getName());
DeptEntity dept = deptRepo.findBy(person.getDeptCode());
entity.setDept(dept);
userRepository.save(entity);
}
}
www.luxoft.com
Code “evolution”
@Service
public class PersonServiceImpl implements PersonService {
@Autowired
private UserRepository userRepository;
@Autowired
private DeptRepository deptRepo;
@Autowired
private MailService mailService;
@Override
public void save(Person person) {
PersonEntity entity = new PersonEntity();
entity.setName(person.getName());
DeptEntity dept = deptRepo.findBy(person.getDeptCode());
entity.setDept(dept);
if (Objects.equals(dept.getCountry(), "UA")) {
mailService.sendNotification(person.getName());
}
userRepository.save(entity);
}
}
www.luxoft.com
TDD
If hard to write the test
then code design is bad
www.luxoft.com
Interview Question
 There is a list of persons
 Select women and children from it
www.luxoft.com
Predicate
@Service
public class PersonServiceImpl implements PersonService {
public static Predicate<Person> VIP =
p -> p.getGender() == FEMALE || p.getAge() <= 16;
@Override
public List<Person> getVips(List<Person> persons) {
return persons.stream().filter(VIP).collect(toList());
}
www.luxoft.com
Predicate Test
public class PredicateTest {
@Test
public void test1() throws Exception {
Person person = new Person("Andriy", MALE, 33);
assertThat(PersonServiceImpl.VIP.test(person), is(false));
}
}
www.luxoft.com
Code “evolution”
@Service
public class PersonServiceImpl implements PersonService {
@Autowired
private UserRepository userRepository;
@Autowired
private DeptRepository deptRepo;
@Autowired
private MailService mailService;
@Override
public void save(Person person) {
PersonEntity entity = new PersonEntity();
entity.setName(person.getName());
entity.setAge(person.getAge());
DeptEntity dept = deptRepo.findBy(person.getDeptCode());
entity.setDept(dept);
if (Objects.equals(dept.getCountry(), "UA")) {
mailService.sendNotification(person.getName());
}
userRepository.save(entity);
}
}
www.luxoft.com
Writing test
public class PersonServiceTest {
@Test
public void testSave() throws Exception {
PersonService service = new PersonServiceImpl();
Person person = new Person("Andriy", MALE, 33, "UA");
service.save(person);
}
}
www.luxoft.com
Writing test
public class DeptRepositoryStub implements DeptRepository {
@Override
public DeptEntity findBy(Object countryCode) {
return new DeptEntity("UA");
}
}
www.luxoft.com
Writing test
public class MailServiceMock implements MailService {
private boolean invoked;
private String name;
@Override
public void sendNotification(String name) {
this.name = name;
invoked = true;
}
public boolean isInvoked() {
return invoked;
}
public String getName() {
return name;
}
}
www.luxoft.com
Writing test
public class PersonServiceTest {
@Test
public void testSave() throws Exception {
DeptRepository deptRepository = new DeptRepositoryStub();
UserRepository userRepository = new UserRepositoryMock();
MailServiceMock mailService = new MailServiceMock();
PersonService service = new PersonServiceImpl(userRepository, deptRepository, mailService);
Person person = new Person("Andriy", MALE, 33, "UA");
service.save(person);
assertThat(mailService.isInvoked(), is(true));
assertThat(mailService.getName(), equalTo("Andriy"));
}
}
www.luxoft.com
Mockito
@RunWith(MockitoJUnitRunner.class)
public class PersonServiceTest {
@InjectMocks
private PersonService service = new PersonServiceImpl();
@Mock
private DeptRepository deptRepository;
@Mock
private UserRepository userRepository;
@Mock
private MailService mailService;
@Test
public void testSave() throws Exception {
when(deptRepository.findBy(anyString()))
.thenReturn(new DeptEntity("UA"));
Person person = new Person("Andriy", MALE, 33, "UA");
service.save(person);
verify(mailService).sendNotification("Andriy");
ArgumentCaptor<PersonEntity> captor = forClass(PersonEntity.class);
verify(userRepository).save(captor.capture());
assertThat(captor.getValue().getAge(), equalTo(33));
}
}
www.luxoft.com
Mockito
@RunWith(MockitoJUnitRunner.class)
public class PersonServiceTest {
@InjectMocks
private PersonService service = new PersonServiceImpl();
@Mock
private DeptRepository deptRepository;
@Mock
private UserRepository userRepository;
@Mock
private MailService mailService;
}
www.luxoft.com
Mockito
@Test
public void testSave() throws Exception {
when(deptRepository.findBy(anyString()))
.thenReturn(new DeptEntity("UA"));
Person person = new Person("Andriy", MALE, 33, "UA");
service.save(person);
verify(mailService).sendNotification("Andriy");
ArgumentCaptor<PersonEntity> captor = forClass(PersonEntity.class);
verify(userRepository).save(captor.capture());
assertThat(captor.getValue().getAge(), equalTo(33));
}
www.luxoft.com
TDD
Think about the test / write it
Before coding the method
www.luxoft.com
THANK YOU

More Related Content

What's hot

Building CRUD Wrappers
Building CRUD WrappersBuilding CRUD Wrappers
Building CRUD Wrappers
OutSystems
 
Bytecode manipulation with Javassist and ASM
Bytecode manipulation with Javassist and ASMBytecode manipulation with Javassist and ASM
Bytecode manipulation with Javassist and ASM
ashleypuls
 
Unit testing with Easymock
Unit testing with EasymockUnit testing with Easymock
Unit testing with Easymock
Ürgo Ringo
 
Groovy And Grails JUG Trento
Groovy And Grails JUG TrentoGroovy And Grails JUG Trento
Groovy And Grails JUG Trento
John Leach
 
COScheduler In Depth
COScheduler In DepthCOScheduler In Depth
COScheduler In Depth
WO Community
 
Club of anonimous developers "Refactoring: Legacy code"
Club of anonimous developers "Refactoring: Legacy code"Club of anonimous developers "Refactoring: Legacy code"
Club of anonimous developers "Refactoring: Legacy code"
Victor_Cr
 
Javantura v2 - Making Java web-apps Groovy - Franjo Žilić
Javantura v2 - Making Java web-apps Groovy - Franjo ŽilićJavantura v2 - Making Java web-apps Groovy - Franjo Žilić
Javantura v2 - Making Java web-apps Groovy - Franjo Žilić
HUJAK - Hrvatska udruga Java korisnika / Croatian Java User Association
 
Javantura v2 - All Together Now - making Groovy and Scala sing together - Din...
Javantura v2 - All Together Now - making Groovy and Scala sing together - Din...Javantura v2 - All Together Now - making Groovy and Scala sing together - Din...
Javantura v2 - All Together Now - making Groovy and Scala sing together - Din...
HUJAK - Hrvatska udruga Java korisnika / Croatian Java User Association
 
SoapUI : Day18 : Webservice- Groovy in soapui : datasink
SoapUI : Day18 : Webservice- Groovy in soapui : datasinkSoapUI : Day18 : Webservice- Groovy in soapui : datasink
SoapUI : Day18 : Webservice- Groovy in soapui : datasink
Testing World
 
Beautiful java script
Beautiful java scriptBeautiful java script
Beautiful java script
Ürgo Ringo
 
Mobile Developers Talks: Delve Mobile
Mobile Developers Talks: Delve MobileMobile Developers Talks: Delve Mobile
Mobile Developers Talks: Delve Mobile
Konstantin Loginov
 
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coinsoft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch
 
Agile Android
Agile AndroidAgile Android
Agile Android
Godfrey Nolan
 
Java Bytecode For Discriminating Developers - GeeCON 2011
Java Bytecode For Discriminating Developers - GeeCON 2011Java Bytecode For Discriminating Developers - GeeCON 2011
Java Bytecode For Discriminating Developers - GeeCON 2011
Anton Arhipov
 
Matteo Vaccari - TDD per Android | Codemotion Milan 2015
Matteo Vaccari - TDD per Android | Codemotion Milan 2015Matteo Vaccari - TDD per Android | Codemotion Milan 2015
Matteo Vaccari - TDD per Android | Codemotion Milan 2015
Codemotion
 
Groovy And Grails JUG Sardegna
Groovy And Grails JUG SardegnaGroovy And Grails JUG Sardegna
Groovy And Grails JUG Sardegna
John Leach
 
Lowering in C#: What really happens with your code?, from NDC Oslo 2019
Lowering in C#: What really happens with your code?, from NDC Oslo 2019Lowering in C#: What really happens with your code?, from NDC Oslo 2019
Lowering in C#: What really happens with your code?, from NDC Oslo 2019
David Wengier
 
Android Design Patterns
Android Design PatternsAndroid Design Patterns
Android Design Patterns
Godfrey Nolan
 
Server1
Server1Server1
Server1
FahriIrawan3
 
Generating characterization tests for legacy code
Generating characterization tests for legacy codeGenerating characterization tests for legacy code
Generating characterization tests for legacy code
Jonas Follesø
 

What's hot (20)

Building CRUD Wrappers
Building CRUD WrappersBuilding CRUD Wrappers
Building CRUD Wrappers
 
Bytecode manipulation with Javassist and ASM
Bytecode manipulation with Javassist and ASMBytecode manipulation with Javassist and ASM
Bytecode manipulation with Javassist and ASM
 
Unit testing with Easymock
Unit testing with EasymockUnit testing with Easymock
Unit testing with Easymock
 
Groovy And Grails JUG Trento
Groovy And Grails JUG TrentoGroovy And Grails JUG Trento
Groovy And Grails JUG Trento
 
COScheduler In Depth
COScheduler In DepthCOScheduler In Depth
COScheduler In Depth
 
Club of anonimous developers "Refactoring: Legacy code"
Club of anonimous developers "Refactoring: Legacy code"Club of anonimous developers "Refactoring: Legacy code"
Club of anonimous developers "Refactoring: Legacy code"
 
Javantura v2 - Making Java web-apps Groovy - Franjo Žilić
Javantura v2 - Making Java web-apps Groovy - Franjo ŽilićJavantura v2 - Making Java web-apps Groovy - Franjo Žilić
Javantura v2 - Making Java web-apps Groovy - Franjo Žilić
 
Javantura v2 - All Together Now - making Groovy and Scala sing together - Din...
Javantura v2 - All Together Now - making Groovy and Scala sing together - Din...Javantura v2 - All Together Now - making Groovy and Scala sing together - Din...
Javantura v2 - All Together Now - making Groovy and Scala sing together - Din...
 
SoapUI : Day18 : Webservice- Groovy in soapui : datasink
SoapUI : Day18 : Webservice- Groovy in soapui : datasinkSoapUI : Day18 : Webservice- Groovy in soapui : datasink
SoapUI : Day18 : Webservice- Groovy in soapui : datasink
 
Beautiful java script
Beautiful java scriptBeautiful java script
Beautiful java script
 
Mobile Developers Talks: Delve Mobile
Mobile Developers Talks: Delve MobileMobile Developers Talks: Delve Mobile
Mobile Developers Talks: Delve Mobile
 
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coinsoft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
 
Agile Android
Agile AndroidAgile Android
Agile Android
 
Java Bytecode For Discriminating Developers - GeeCON 2011
Java Bytecode For Discriminating Developers - GeeCON 2011Java Bytecode For Discriminating Developers - GeeCON 2011
Java Bytecode For Discriminating Developers - GeeCON 2011
 
Matteo Vaccari - TDD per Android | Codemotion Milan 2015
Matteo Vaccari - TDD per Android | Codemotion Milan 2015Matteo Vaccari - TDD per Android | Codemotion Milan 2015
Matteo Vaccari - TDD per Android | Codemotion Milan 2015
 
Groovy And Grails JUG Sardegna
Groovy And Grails JUG SardegnaGroovy And Grails JUG Sardegna
Groovy And Grails JUG Sardegna
 
Lowering in C#: What really happens with your code?, from NDC Oslo 2019
Lowering in C#: What really happens with your code?, from NDC Oslo 2019Lowering in C#: What really happens with your code?, from NDC Oslo 2019
Lowering in C#: What really happens with your code?, from NDC Oslo 2019
 
Android Design Patterns
Android Design PatternsAndroid Design Patterns
Android Design Patterns
 
Server1
Server1Server1
Server1
 
Generating characterization tests for legacy code
Generating characterization tests for legacy codeGenerating characterization tests for legacy code
Generating characterization tests for legacy code
 

Similar to Андрей Слободяник "Test driven development using mockito"

比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
javatwo2011
 
Testdrevet javautvikling på objektorienterte skinner
Testdrevet javautvikling på objektorienterte skinnerTestdrevet javautvikling på objektorienterte skinner
Testdrevet javautvikling på objektorienterte skinner
Truls Jørgensen
 
CouchDB on Android
CouchDB on AndroidCouchDB on Android
CouchDB on Android
Sven Haiges
 
Testing in android
Testing in androidTesting in android
Testing in android
jtrindade
 
Coding Ajax
Coding AjaxCoding Ajax
Coding Ajax
Ted Husted
 
Http4s, Doobie and Circe: The Functional Web Stack
Http4s, Doobie and Circe: The Functional Web StackHttp4s, Doobie and Circe: The Functional Web Stack
Http4s, Doobie and Circe: The Functional Web Stack
GaryCoady
 
Coding Ajax
Coding AjaxCoding Ajax
Coding Ajax
Ted Husted
 
droidparts
droidpartsdroidparts
droidparts
Droidcon Berlin
 
Тарас Олексин - Sculpt! Your! Tests!
Тарас Олексин  - Sculpt! Your! Tests!Тарас Олексин  - Sculpt! Your! Tests!
Тарас Олексин - Sculpt! Your! Tests!
DataArt
 
Painless Persistence with Realm
Painless Persistence with RealmPainless Persistence with Realm
Painless Persistence with Realm
Christian Melchior
 
SOLID Principles
SOLID PrinciplesSOLID Principles
SOLID Principles
Chris Weldon
 
Easy data-with-spring-data-jpa
Easy data-with-spring-data-jpaEasy data-with-spring-data-jpa
Easy data-with-spring-data-jpa
Staples
 
Typescript - why it's awesome
Typescript - why it's awesomeTypescript - why it's awesome
Typescript - why it's awesome
Piotr Miazga
 
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScriptjQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
Guy Royse
 
Getting started with Elasticsearch and .NET
Getting started with Elasticsearch and .NETGetting started with Elasticsearch and .NET
Getting started with Elasticsearch and .NET
Tomas Jansson
 
Atlassian Groovy Plugins
Atlassian Groovy PluginsAtlassian Groovy Plugins
Atlassian Groovy Plugins
Paul King
 
Teste de Integração com DbUnit e jIntegrity
Teste de Integração com DbUnit e jIntegrityTeste de Integração com DbUnit e jIntegrity
Teste de Integração com DbUnit e jIntegrity
Washington Botelho
 
Using the Windows 8 Runtime from C++
Using the Windows 8 Runtime from C++Using the Windows 8 Runtime from C++
Bigger Stronger Faster
Bigger Stronger FasterBigger Stronger Faster
Bigger Stronger Faster
Chris Love
 
E:\Plp 2009 2\Plp 9
E:\Plp 2009 2\Plp 9E:\Plp 2009 2\Plp 9
E:\Plp 2009 2\Plp 9
Ismar Silveira
 

Similar to Андрей Слободяник "Test driven development using mockito" (20)

比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
 
Testdrevet javautvikling på objektorienterte skinner
Testdrevet javautvikling på objektorienterte skinnerTestdrevet javautvikling på objektorienterte skinner
Testdrevet javautvikling på objektorienterte skinner
 
CouchDB on Android
CouchDB on AndroidCouchDB on Android
CouchDB on Android
 
Testing in android
Testing in androidTesting in android
Testing in android
 
Coding Ajax
Coding AjaxCoding Ajax
Coding Ajax
 
Http4s, Doobie and Circe: The Functional Web Stack
Http4s, Doobie and Circe: The Functional Web StackHttp4s, Doobie and Circe: The Functional Web Stack
Http4s, Doobie and Circe: The Functional Web Stack
 
Coding Ajax
Coding AjaxCoding Ajax
Coding Ajax
 
droidparts
droidpartsdroidparts
droidparts
 
Тарас Олексин - Sculpt! Your! Tests!
Тарас Олексин  - Sculpt! Your! Tests!Тарас Олексин  - Sculpt! Your! Tests!
Тарас Олексин - Sculpt! Your! Tests!
 
Painless Persistence with Realm
Painless Persistence with RealmPainless Persistence with Realm
Painless Persistence with Realm
 
SOLID Principles
SOLID PrinciplesSOLID Principles
SOLID Principles
 
Easy data-with-spring-data-jpa
Easy data-with-spring-data-jpaEasy data-with-spring-data-jpa
Easy data-with-spring-data-jpa
 
Typescript - why it's awesome
Typescript - why it's awesomeTypescript - why it's awesome
Typescript - why it's awesome
 
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScriptjQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
 
Getting started with Elasticsearch and .NET
Getting started with Elasticsearch and .NETGetting started with Elasticsearch and .NET
Getting started with Elasticsearch and .NET
 
Atlassian Groovy Plugins
Atlassian Groovy PluginsAtlassian Groovy Plugins
Atlassian Groovy Plugins
 
Teste de Integração com DbUnit e jIntegrity
Teste de Integração com DbUnit e jIntegrityTeste de Integração com DbUnit e jIntegrity
Teste de Integração com DbUnit e jIntegrity
 
Using the Windows 8 Runtime from C++
Using the Windows 8 Runtime from C++Using the Windows 8 Runtime from C++
Using the Windows 8 Runtime from C++
 
Bigger Stronger Faster
Bigger Stronger FasterBigger Stronger Faster
Bigger Stronger Faster
 
E:\Plp 2009 2\Plp 9
E:\Plp 2009 2\Plp 9E:\Plp 2009 2\Plp 9
E:\Plp 2009 2\Plp 9
 

More from Anna Shymchenko

Константин Маркович: "Creating modular application using Spring Boot "
Константин Маркович: "Creating modular application using Spring Boot "Константин Маркович: "Creating modular application using Spring Boot "
Константин Маркович: "Creating modular application using Spring Boot "
Anna Shymchenko
 
Евгений Бова: "Modularity in Java: introduction to Jigsaw through the prism o...
Евгений Бова: "Modularity in Java: introduction to Jigsaw through the prism o...Евгений Бова: "Modularity in Java: introduction to Jigsaw through the prism o...
Евгений Бова: "Modularity in Java: introduction to Jigsaw through the prism o...
Anna Shymchenko
 
Евгений Руднев: "Programmers Approach to Error Handling"
Евгений Руднев: "Programmers Approach to Error Handling"Евгений Руднев: "Programmers Approach to Error Handling"
Евгений Руднев: "Programmers Approach to Error Handling"
Anna Shymchenko
 
Александр Куцан: "Static Code Analysis in C++"
Александр Куцан: "Static Code Analysis in C++" Александр Куцан: "Static Code Analysis in C++"
Александр Куцан: "Static Code Analysis in C++"
Anna Shymchenko
 
Алесей Решта: “Robotics Sport & Luxoft Open Robotics Club”
Алесей Решта: “Robotics Sport & Luxoft Open Robotics Club” Алесей Решта: “Robotics Sport & Luxoft Open Robotics Club”
Алесей Решта: “Robotics Sport & Luxoft Open Robotics Club”
Anna Shymchenko
 
Орхан Гасимов: "Reactive Applications in Java with Akka"
Орхан Гасимов: "Reactive Applications in Java with Akka"Орхан Гасимов: "Reactive Applications in Java with Akka"
Орхан Гасимов: "Reactive Applications in Java with Akka"
Anna Shymchenko
 
Евгений Хыст: "Server-Side Geo-Clustering Based on Geohash"
Евгений Хыст: "Server-Side Geo-Clustering Based on Geohash"Евгений Хыст: "Server-Side Geo-Clustering Based on Geohash"
Евгений Хыст: "Server-Side Geo-Clustering Based on Geohash"
Anna Shymchenko
 
Денис Прокопюк: “JMX in Java EE applications”
Денис Прокопюк: “JMX in Java EE applications”Денис Прокопюк: “JMX in Java EE applications”
Денис Прокопюк: “JMX in Java EE applications”
Anna Shymchenko
 
Роман Яворский "Introduction to DevOps"
Роман Яворский "Introduction to DevOps"Роман Яворский "Introduction to DevOps"
Роман Яворский "Introduction to DevOps"
Anna Shymchenko
 
Максим Сабарня “NoSQL: Not only SQL in developer’s life”
Максим Сабарня “NoSQL: Not only SQL in developer’s life” Максим Сабарня “NoSQL: Not only SQL in developer’s life”
Максим Сабарня “NoSQL: Not only SQL in developer’s life”
Anna Shymchenko
 
Андрей Лисниченко "SQL Injection"
Андрей Лисниченко "SQL Injection"Андрей Лисниченко "SQL Injection"
Андрей Лисниченко "SQL Injection"
Anna Shymchenko
 
Светлана Мухина "Metrics on agile projects"
Светлана Мухина "Metrics on agile projects"Светлана Мухина "Metrics on agile projects"
Светлана Мухина "Metrics on agile projects"
Anna Shymchenko
 
Евгений Хыст "Application performance database related problems"
Евгений Хыст "Application performance database related problems"Евгений Хыст "Application performance database related problems"
Евгений Хыст "Application performance database related problems"
Anna Shymchenko
 
Даурен Муса “IBM WebSphere - expensive but effective”
Даурен Муса “IBM WebSphere - expensive but effective” Даурен Муса “IBM WebSphere - expensive but effective”
Даурен Муса “IBM WebSphere - expensive but effective”
Anna Shymchenko
 
Александр Пашинский "Reinventing Design Patterns with Java 8"
Александр Пашинский "Reinventing Design Patterns with Java 8"Александр Пашинский "Reinventing Design Patterns with Java 8"
Александр Пашинский "Reinventing Design Patterns with Java 8"
Anna Shymchenko
 
Евгений Капинос "Advanced JPA (Java Persistent API)"
Евгений Капинос "Advanced JPA (Java Persistent API)"Евгений Капинос "Advanced JPA (Java Persistent API)"
Евгений Капинос "Advanced JPA (Java Persistent API)"
Anna Shymchenko
 
Event-driven architecture with Java technology stack
Event-driven architecture with Java technology stackEvent-driven architecture with Java technology stack
Event-driven architecture with Java technology stack
Anna Shymchenko
 
Do we need SOLID principles during software development?
Do we need SOLID principles during software development?Do we need SOLID principles during software development?
Do we need SOLID principles during software development?
Anna Shymchenko
 
Guava - Elements of Functional Programming
Guava - Elements of Functional Programming Guava - Elements of Functional Programming
Guava - Elements of Functional Programming
Anna Shymchenko
 
Максим Сабарня и Иван Дрижирук “Vert.x – tool-kit for building reactive app...
 	Максим Сабарня и Иван Дрижирук “Vert.x – tool-kit for building reactive app... 	Максим Сабарня и Иван Дрижирук “Vert.x – tool-kit for building reactive app...
Максим Сабарня и Иван Дрижирук “Vert.x – tool-kit for building reactive app...
Anna Shymchenko
 

More from Anna Shymchenko (20)

Константин Маркович: "Creating modular application using Spring Boot "
Константин Маркович: "Creating modular application using Spring Boot "Константин Маркович: "Creating modular application using Spring Boot "
Константин Маркович: "Creating modular application using Spring Boot "
 
Евгений Бова: "Modularity in Java: introduction to Jigsaw through the prism o...
Евгений Бова: "Modularity in Java: introduction to Jigsaw through the prism o...Евгений Бова: "Modularity in Java: introduction to Jigsaw through the prism o...
Евгений Бова: "Modularity in Java: introduction to Jigsaw through the prism o...
 
Евгений Руднев: "Programmers Approach to Error Handling"
Евгений Руднев: "Programmers Approach to Error Handling"Евгений Руднев: "Programmers Approach to Error Handling"
Евгений Руднев: "Programmers Approach to Error Handling"
 
Александр Куцан: "Static Code Analysis in C++"
Александр Куцан: "Static Code Analysis in C++" Александр Куцан: "Static Code Analysis in C++"
Александр Куцан: "Static Code Analysis in C++"
 
Алесей Решта: “Robotics Sport & Luxoft Open Robotics Club”
Алесей Решта: “Robotics Sport & Luxoft Open Robotics Club” Алесей Решта: “Robotics Sport & Luxoft Open Robotics Club”
Алесей Решта: “Robotics Sport & Luxoft Open Robotics Club”
 
Орхан Гасимов: "Reactive Applications in Java with Akka"
Орхан Гасимов: "Reactive Applications in Java with Akka"Орхан Гасимов: "Reactive Applications in Java with Akka"
Орхан Гасимов: "Reactive Applications in Java with Akka"
 
Евгений Хыст: "Server-Side Geo-Clustering Based on Geohash"
Евгений Хыст: "Server-Side Geo-Clustering Based on Geohash"Евгений Хыст: "Server-Side Geo-Clustering Based on Geohash"
Евгений Хыст: "Server-Side Geo-Clustering Based on Geohash"
 
Денис Прокопюк: “JMX in Java EE applications”
Денис Прокопюк: “JMX in Java EE applications”Денис Прокопюк: “JMX in Java EE applications”
Денис Прокопюк: “JMX in Java EE applications”
 
Роман Яворский "Introduction to DevOps"
Роман Яворский "Introduction to DevOps"Роман Яворский "Introduction to DevOps"
Роман Яворский "Introduction to DevOps"
 
Максим Сабарня “NoSQL: Not only SQL in developer’s life”
Максим Сабарня “NoSQL: Not only SQL in developer’s life” Максим Сабарня “NoSQL: Not only SQL in developer’s life”
Максим Сабарня “NoSQL: Not only SQL in developer’s life”
 
Андрей Лисниченко "SQL Injection"
Андрей Лисниченко "SQL Injection"Андрей Лисниченко "SQL Injection"
Андрей Лисниченко "SQL Injection"
 
Светлана Мухина "Metrics on agile projects"
Светлана Мухина "Metrics on agile projects"Светлана Мухина "Metrics on agile projects"
Светлана Мухина "Metrics on agile projects"
 
Евгений Хыст "Application performance database related problems"
Евгений Хыст "Application performance database related problems"Евгений Хыст "Application performance database related problems"
Евгений Хыст "Application performance database related problems"
 
Даурен Муса “IBM WebSphere - expensive but effective”
Даурен Муса “IBM WebSphere - expensive but effective” Даурен Муса “IBM WebSphere - expensive but effective”
Даурен Муса “IBM WebSphere - expensive but effective”
 
Александр Пашинский "Reinventing Design Patterns with Java 8"
Александр Пашинский "Reinventing Design Patterns with Java 8"Александр Пашинский "Reinventing Design Patterns with Java 8"
Александр Пашинский "Reinventing Design Patterns with Java 8"
 
Евгений Капинос "Advanced JPA (Java Persistent API)"
Евгений Капинос "Advanced JPA (Java Persistent API)"Евгений Капинос "Advanced JPA (Java Persistent API)"
Евгений Капинос "Advanced JPA (Java Persistent API)"
 
Event-driven architecture with Java technology stack
Event-driven architecture with Java technology stackEvent-driven architecture with Java technology stack
Event-driven architecture with Java technology stack
 
Do we need SOLID principles during software development?
Do we need SOLID principles during software development?Do we need SOLID principles during software development?
Do we need SOLID principles during software development?
 
Guava - Elements of Functional Programming
Guava - Elements of Functional Programming Guava - Elements of Functional Programming
Guava - Elements of Functional Programming
 
Максим Сабарня и Иван Дрижирук “Vert.x – tool-kit for building reactive app...
 	Максим Сабарня и Иван Дрижирук “Vert.x – tool-kit for building reactive app... 	Максим Сабарня и Иван Дрижирук “Vert.x – tool-kit for building reactive app...
Максим Сабарня и Иван Дрижирук “Vert.x – tool-kit for building reactive app...
 

Recently uploaded

J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
Bert Jan Schrijver
 
Using Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional SafetyUsing Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional Safety
Ayan Halder
 
Lecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptxLecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptx
TaghreedAltamimi
 
How to write a program in any programming language
How to write a program in any programming languageHow to write a program in any programming language
How to write a program in any programming language
Rakesh Kumar R
 
Oracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptxOracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptx
Remote DBA Services
 
Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)
Julian Hyde
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
Drona Infotech
 
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
dakas1
 
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
mz5nrf0n
 
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
Łukasz Chruściel
 
SMS API Integration in Saudi Arabia| Best SMS API Service
SMS API Integration in Saudi Arabia| Best SMS API ServiceSMS API Integration in Saudi Arabia| Best SMS API Service
SMS API Integration in Saudi Arabia| Best SMS API Service
Yara Milbes
 
SQL Accounting Software Brochure Malaysia
SQL Accounting Software Brochure MalaysiaSQL Accounting Software Brochure Malaysia
SQL Accounting Software Brochure Malaysia
GohKiangHock
 
Top 9 Trends in Cybersecurity for 2024.pptx
Top 9 Trends in Cybersecurity for 2024.pptxTop 9 Trends in Cybersecurity for 2024.pptx
Top 9 Trends in Cybersecurity for 2024.pptx
devvsandy
 
Transform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR SolutionsTransform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR Solutions
TheSMSPoint
 
UI5con 2024 - Bring Your Own Design System
UI5con 2024 - Bring Your Own Design SystemUI5con 2024 - Bring Your Own Design System
UI5con 2024 - Bring Your Own Design System
Peter Muessig
 
Webinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for EmbeddedWebinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for Embedded
ICS
 
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s EcosystemUI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
Peter Muessig
 
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling ExtensionsUI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
Peter Muessig
 
Modelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - AmsterdamModelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - Amsterdam
Alberto Brandolini
 
Odoo ERP Vs. Traditional ERP Systems – A Comparative Analysis
Odoo ERP Vs. Traditional ERP Systems – A Comparative AnalysisOdoo ERP Vs. Traditional ERP Systems – A Comparative Analysis
Odoo ERP Vs. Traditional ERP Systems – A Comparative Analysis
Envertis Software Solutions
 

Recently uploaded (20)

J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
 
Using Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional SafetyUsing Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional Safety
 
Lecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptxLecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptx
 
How to write a program in any programming language
How to write a program in any programming languageHow to write a program in any programming language
How to write a program in any programming language
 
Oracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptxOracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptx
 
Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
 
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
 
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
 
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
 
SMS API Integration in Saudi Arabia| Best SMS API Service
SMS API Integration in Saudi Arabia| Best SMS API ServiceSMS API Integration in Saudi Arabia| Best SMS API Service
SMS API Integration in Saudi Arabia| Best SMS API Service
 
SQL Accounting Software Brochure Malaysia
SQL Accounting Software Brochure MalaysiaSQL Accounting Software Brochure Malaysia
SQL Accounting Software Brochure Malaysia
 
Top 9 Trends in Cybersecurity for 2024.pptx
Top 9 Trends in Cybersecurity for 2024.pptxTop 9 Trends in Cybersecurity for 2024.pptx
Top 9 Trends in Cybersecurity for 2024.pptx
 
Transform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR SolutionsTransform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR Solutions
 
UI5con 2024 - Bring Your Own Design System
UI5con 2024 - Bring Your Own Design SystemUI5con 2024 - Bring Your Own Design System
UI5con 2024 - Bring Your Own Design System
 
Webinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for EmbeddedWebinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for Embedded
 
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s EcosystemUI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
 
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling ExtensionsUI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
 
Modelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - AmsterdamModelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - Amsterdam
 
Odoo ERP Vs. Traditional ERP Systems – A Comparative Analysis
Odoo ERP Vs. Traditional ERP Systems – A Comparative AnalysisOdoo ERP Vs. Traditional ERP Systems – A Comparative Analysis
Odoo ERP Vs. Traditional ERP Systems – A Comparative Analysis
 

Андрей Слободяник "Test driven development using mockito"

  • 1. www.luxoft.com Test Driven Development Using Mockito By Andriy Slobodyanyk
  • 2. www.luxoft.com About me Andriy Slobodyanyk  Some years in Java Development  Even TechLead of Luxoft team  Bench press max 118 kg
  • 5. www.luxoft.com Interview Question  There is a list of persons  Select women and children from it
  • 6. www.luxoft.com Predicate public List<Person> getVips(List<Person> persons) { List<Person> result = new ArrayList<Person>(); for (Person p : persons) { if (p.getGender() == FEMALE && p.getAge() > 16) { result.add(p); } } return result; }
  • 7. www.luxoft.com TDD If hard to write the test then code design is bad
  • 8. www.luxoft.com Code “evolution” @Service public class PersonServiceImpl implements PersonService { @Autowired private UserRepository userRepository; @Override public void save(Person person) { PersonEntity entity = new PersonEntity(); entity.setName(person.getName()); userRepository.save(entity); } }
  • 9. www.luxoft.com Code “evolution” @Service public class PersonServiceImpl implements PersonService { @Autowired private UserRepository userRepository; @Autowired private DeptRepository deptRepo; @Override public void save(Person person) { PersonEntity entity = new PersonEntity(); entity.setName(person.getName()); DeptEntity dept = deptRepo.findBy(person.getDeptCode()); entity.setDept(dept); userRepository.save(entity); } }
  • 10. www.luxoft.com Code “evolution” @Service public class PersonServiceImpl implements PersonService { @Autowired private UserRepository userRepository; @Autowired private DeptRepository deptRepo; @Autowired private MailService mailService; @Override public void save(Person person) { PersonEntity entity = new PersonEntity(); entity.setName(person.getName()); DeptEntity dept = deptRepo.findBy(person.getDeptCode()); entity.setDept(dept); if (Objects.equals(dept.getCountry(), "UA")) { mailService.sendNotification(person.getName()); } userRepository.save(entity); } }
  • 11. www.luxoft.com TDD If hard to write the test then code design is bad
  • 12. www.luxoft.com Interview Question  There is a list of persons  Select women and children from it
  • 13. www.luxoft.com Predicate @Service public class PersonServiceImpl implements PersonService { public static Predicate<Person> VIP = p -> p.getGender() == FEMALE || p.getAge() <= 16; @Override public List<Person> getVips(List<Person> persons) { return persons.stream().filter(VIP).collect(toList()); }
  • 14. www.luxoft.com Predicate Test public class PredicateTest { @Test public void test1() throws Exception { Person person = new Person("Andriy", MALE, 33); assertThat(PersonServiceImpl.VIP.test(person), is(false)); } }
  • 15. www.luxoft.com Code “evolution” @Service public class PersonServiceImpl implements PersonService { @Autowired private UserRepository userRepository; @Autowired private DeptRepository deptRepo; @Autowired private MailService mailService; @Override public void save(Person person) { PersonEntity entity = new PersonEntity(); entity.setName(person.getName()); entity.setAge(person.getAge()); DeptEntity dept = deptRepo.findBy(person.getDeptCode()); entity.setDept(dept); if (Objects.equals(dept.getCountry(), "UA")) { mailService.sendNotification(person.getName()); } userRepository.save(entity); } }
  • 16. www.luxoft.com Writing test public class PersonServiceTest { @Test public void testSave() throws Exception { PersonService service = new PersonServiceImpl(); Person person = new Person("Andriy", MALE, 33, "UA"); service.save(person); } }
  • 17. www.luxoft.com Writing test public class DeptRepositoryStub implements DeptRepository { @Override public DeptEntity findBy(Object countryCode) { return new DeptEntity("UA"); } }
  • 18. www.luxoft.com Writing test public class MailServiceMock implements MailService { private boolean invoked; private String name; @Override public void sendNotification(String name) { this.name = name; invoked = true; } public boolean isInvoked() { return invoked; } public String getName() { return name; } }
  • 19. www.luxoft.com Writing test public class PersonServiceTest { @Test public void testSave() throws Exception { DeptRepository deptRepository = new DeptRepositoryStub(); UserRepository userRepository = new UserRepositoryMock(); MailServiceMock mailService = new MailServiceMock(); PersonService service = new PersonServiceImpl(userRepository, deptRepository, mailService); Person person = new Person("Andriy", MALE, 33, "UA"); service.save(person); assertThat(mailService.isInvoked(), is(true)); assertThat(mailService.getName(), equalTo("Andriy")); } }
  • 20. www.luxoft.com Mockito @RunWith(MockitoJUnitRunner.class) public class PersonServiceTest { @InjectMocks private PersonService service = new PersonServiceImpl(); @Mock private DeptRepository deptRepository; @Mock private UserRepository userRepository; @Mock private MailService mailService; @Test public void testSave() throws Exception { when(deptRepository.findBy(anyString())) .thenReturn(new DeptEntity("UA")); Person person = new Person("Andriy", MALE, 33, "UA"); service.save(person); verify(mailService).sendNotification("Andriy"); ArgumentCaptor<PersonEntity> captor = forClass(PersonEntity.class); verify(userRepository).save(captor.capture()); assertThat(captor.getValue().getAge(), equalTo(33)); } }
  • 21. www.luxoft.com Mockito @RunWith(MockitoJUnitRunner.class) public class PersonServiceTest { @InjectMocks private PersonService service = new PersonServiceImpl(); @Mock private DeptRepository deptRepository; @Mock private UserRepository userRepository; @Mock private MailService mailService; }
  • 22. www.luxoft.com Mockito @Test public void testSave() throws Exception { when(deptRepository.findBy(anyString())) .thenReturn(new DeptEntity("UA")); Person person = new Person("Andriy", MALE, 33, "UA"); service.save(person); verify(mailService).sendNotification("Andriy"); ArgumentCaptor<PersonEntity> captor = forClass(PersonEntity.class); verify(userRepository).save(captor.capture()); assertThat(captor.getValue().getAge(), equalTo(33)); }
  • 23. www.luxoft.com TDD Think about the test / write it Before coding the method