Instant Download Mockito for Spring 1st Edition Acharya Sujoy PDF All Chapters
Instant Download Mockito for Spring 1st Edition Acharya Sujoy PDF All Chapters
com
https://textbookfull.com/product/mockito-for-spring-1st-
edition-acharya-sujoy/
OR CLICK BUTTON
DOWNLOAD NOW
https://textbookfull.com/product/spring-quick-reference-guide-a-
pocket-handbook-for-spring-framework-spring-boot-and-more-adam-l-
davis/
textboxfull.com
https://textbookfull.com/product/instability-in-flow-boiling-in-
microchannels-1st-edition-sujoy-kumar-saha/
textboxfull.com
https://textbookfull.com/product/marginalization-in-globalizing-delhi-
issues-of-land-livelihoods-and-health-1st-edition-sanghmitra-s-
acharya/
textboxfull.com
https://textbookfull.com/product/two-phase-heat-transfer-enhancement-
sujoy-kumar-saha/
textboxfull.com
https://textbookfull.com/product/mountain-spring-fever-spring-s-
mountain-men-1st-edition-andrea-marie-marie-andrea/
textboxfull.com
https://textbookfull.com/product/performance-evaluation-criteria-in-
heat-transfer-enhancement-sujoy-kumar-saha/
textboxfull.com
https://textbookfull.com/product/spring-data-1st-edition-petri-
kainulainen/
textboxfull.com
https://textbookfull.com/product/spring-cookbook-1st-edition-jaglale-
jerome/
textboxfull.com
Mockito for Spring
Sujoy Acharya
BIRMINGHAM - MUMBAI
Mockito for Spring
All rights reserved. No part of this book may be reproduced, stored in a retrieval
system, or transmitted in any form or by any means, without the prior written
permission of the publisher, except in the case of brief quotations embedded in
critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy
of the information presented. However, the information contained in this book is
sold without warranty, either express or implied. Neither the author, nor Packt
Publishing, and its dealers and distributors will be held liable for any damages
caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the
companies and products mentioned in this book by the appropriate use of capitals.
However, Packt Publishing cannot guarantee the accuracy of this information.
ISBN 978-1-78398-378-0
www.packtpub.com
Credits
Reviewers Proofreaders
Carlo Micieli Martin Diver
Gualtiero Testa Maria Gould
Paul Hindle
Commissioning Editor
Amarabha Banerjee Indexer
Monica Ajmera Mehta
Acquisition Editor
Llewellyn Rozario Production Coordinator
Aparna Bhagat
Content Development Editor
Parita Khedekar Cover Work
Aparna Bhagat
Technical Editors
Manal Pednekar
Chinmay S. Puranik
Copy Editors
Dipti Kapadia
Deepa Nambiar
Vikrant Phadke
About the Author
Sujoy likes to research upcoming technologies. His major contributions are in the
fields of Java, J2EE, SOA, Ajax, GWT, and the Spring Framework.
He has authored three books for Packt Publishing, namely Test-Driven Development
with Mockito, Mastering Unit Testing using Mockito and JUnit, and Mockito Essentials.
I would also like to thank my mother and late father for their
support, blessings, and encouragement.
Carlo Micieli has been a software developer since 2001, developing applications
for computer-aided manufacturing with C#.
His main area of interest is application life cycle management, with a strong focus on
topics such as software design and testing.
He is a programming languages enthusiast, and he's currently trying to learn Scala and
Haskell. He shares his experiments on GitHub (http://github.com/CarloMicieli).
His main interests are test-driven development (TDD), testing tools and
methodologies, and everything related to code quality.
Did you know that Packt offers eBook versions of every book published, with PDF
and ePub files available? You can upgrade to the eBook version at www.PacktPub.
com and as a print book customer, you are entitled to a discount on the eBook copy.
Get in touch with us at service@packtpub.com for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign
up for a range of free newsletters, and receive exclusive discounts and offers on
Packt books and eBooks.
TM
https://www2.packtpub.com/books/subscription/packtlib
Do you need instant solutions to your IT questions? PacktLib is Packt's online digital
book library. Here, you can search, access, and read Packt's entire library of books.
Why subscribe?
• Fully searchable across every book published by Packt
• Copy and paste, print, and bookmark content
• On demand and accessible via a web browser
[ ii ]
Table of Contents
[ iii ]
Preface
When I was writing the first draft of this book, I was eager to compare the
manuscript with other books on the Spring Framework. Here are the features
that distinguish this book from others:
• This book is not only about the Spring Framework. It also describes the basics
of Spring, Spring's test module, Spring's integration testing, JUnit testing,
how to mock Spring beans with Mockito, and advanced Spring 4.1 features.
I couldn't find any books that cover these topics.
• This book explains JUnit testing and mocking in the context of Spring.
• The book covers Spring's test module and Spring integration testing in detail.
These are the most difficult parts in the Spring testing world.
Chapter 2, Working with JUnit and Mockito, covers both basic and advanced JUnit
usages. It covers annotation-based JUnit testing, assertion, the @RunWith annotation,
exception handling, and the Eclipse setup to run JUnit tests, matchers, and
assertThat, as well as the custom lessThanOrEqual() matcher. The Working
with Mockito section explores the Mockito framework and provides technical
examples to demonstrate the capability of Mockito.
Preface
Chapter 3, Working with Spring Tests, illustrates every aspect of unit testing your
Spring applications. It starts with TestContext and explores the JUnit 4 enabled
SpringJUnit4ClassRunner. Then, it explores Spring profiles that can be used to
work with the different sets of configuration files as well as the Spring environment
and how to mock the environment with MockEnvironment and MockPropertySource.
We use the ReflectionTestUtils method to access the private fields of the Spring
beans. The chapter provides usage examples of Spring annotations for testing, unit
tests the MVC application with MockHttpServletRequest, MockHttpSession, and
ModelAndViewAssert, and mocks the servlet container with MockMvc to handle actual
requests and responses, as they will be at runtime. You will also perform real Spring
integration and transaction management with annotations such as @Transactional,
@TransactionConfiguration, and @Rollback.
Chapter 4, Resolving Out-of-container Dependencies with Mockito, deals with unit testing
the service layer in isolation from the data access layer with Mockito, unit testing the
Spring data access layer with Mockito, and unit testing the Spring presentation layer
(MVC) with Mockito.
Chapter 5, Time Travelling with Spring, starts by covering the features of the new major
Spring release 4.0, such as Java 8 support and so on. Then, we pick the four Spring
4 topics and explore them one by one. The Working with asynchronous tasks section
showcases the execution of long running methods asynchronously and provides
examples to handle asynchronous processing. The Exploring @RestController section
eases RESTful web service development with the advent of the @RestController
annotation. The Learning AsyncRestTemplate section explains the RESTful client code
to invoke RESTful web services asynchronously. Caching is inevitable for high
performant, scalable web applications. This section explains EhCache and Spring
integration to achieve a high availability caching solution.
[2]
Preface
It is ideal for developers who have some experience in Java application development
and the Spring Framework as well as some basic knowledge of JUnit testing. However,
it also covers the basic fundamentals of JUnit testing, the Spring Framework, and the
Mockito framework to get you acquainted with these concepts before you use them.
Conventions
In this book, you will find a number of styles of text that distinguish between
different kinds of information. Here are some examples of these styles, and an
explanation of their meaning.
Code words in text, database table names, folder names, filenames, file extensions,
pathnames, dummy URLs, user input, and Twitter handles are shown as follows:
"The messaging module comes with key abstractions from the Spring Integration
project such as Message, MessageChannel, and MessageHandler to serve as a
foundation for messaging-based applications."
When we wish to draw your attention to a particular part of a code block, the
relevant lines or items are set in bold:
public class LocaleTest {
private Locale defaultLocale;
@Before
public void setUp() {
defaultLocale = Locale.getDefault();
Locale.setDefault(Locale.GERMANY);
}
[3]
Preface
@After
public void restore() {
Locale.setDefault(defaultLocale);
}
@Test
public void currencyRoundsOff() throws Exception {
assertEquals("$101.00", CurrencyFormatter.format(100.999));
}
}
New terms and important words are shown in bold. Words that you see on the
screen, in menus or dialog boxes for example, appear in the text like this: "Right-click
on the project; a pop-up menu will appear. Expand the Build Path menu and click on
the Configure Build Path menu item."
Reader feedback
Feedback from our readers is always welcome. Let us know what you think about
this book—what you liked or may have disliked. Reader feedback is important for
us to develop titles that you really get the most out of.
If there is a topic that you have expertise in and you are interested in either writing
or contributing to a book, see our author guide on www.packtpub.com/authors.
Customer support
Now that you are the proud owner of a Packt book, we have a number of things to
help you to get the most from your purchase.
[4]
Preface
Errata
Although we have taken every care to ensure the accuracy of our content, mistakes do
happen. If you find a mistake in one of our books—maybe a mistake in the text or the
code—we would be grateful if you would report this to us. By doing so, you can save
other readers from frustration and help us improve subsequent versions of this book.
If you find any errata, please report them by visiting http://www.packtpub.com/
submit-errata, selecting your book, clicking on the errata submission form link,
and entering the details of your errata. Once your errata are verified, your submission
will be accepted and the errata will be uploaded on our website, or added to any list
of existing errata, under the Errata section of that title. Any existing errata can be
viewed by selecting your title from http://www.packtpub.com/support.
Piracy
Piracy of copyright material on the Internet is an ongoing problem across all media.
At Packt, we take the protection of our copyright and licenses very seriously. If you
come across any illegal copies of our works, in any form, on the Internet, please
provide us with the location address or website name immediately so that we
can pursue a remedy.
We appreciate your help in protecting our authors, and our ability to bring you
valuable content.
Questions
You can contact us at questions@packtpub.com if you are having a problem with
any aspect of the book, and we will do our best to address it.
[5]
Getting Familiar with
the Spring Framework
Spring is a popular enterprise application development framework. This chapter
covers the following topics:
• A Java method can handle an HTTP POST/GET request; you don't have to
write a servlet or work with servlet APIs
• A Java method can act as a RESTful web service without dealing with web
service APIs
• A Java method can execute a database transaction without dealing with
transaction APIs
• A local Java method can participate in a remote procedure call (RPC)
without having to deal with remote APIs
• A Java method can consume or handle messages without having to deal with
JMS APIs
• A Java method can work as a management extension without dealing with
JMX APIs
[8]
Chapter 1
There are various Spring projects that can be used. In this book, we'll be using
Spring 4.
IO PLATFORM BOOT
SPRING FRAMEWORK SPRING XD
SPRING CLOUD
INTEGRATION BATCH
SPRING DATA
• The Spring IO platform: Spring IO brings together the core Spring APIs into
a cohesive and versioned foundational platform for modern applications.
Spring IO is comprised of the Spring IO Foundation and Spring IO
Execution layers.
• Spring Boot: This helps in creating production-grade Spring applications
that can be run any time with the minimal Spring configuration. It follows
the convention-over-configuration approach.
[9]
Getting Familiar with the Spring Framework
[ 10 ]
Chapter 1
• Core and Beans: These provide the fundamental parts of the framework,
including IoC and dependency injection features
• Context: This is a means to access objects in a framework-style manner that is
similar to the JNDI registry
• Expression Language: This is also known as SpEL; it is an expression
language used to query and modify an object graph and evaluate
mathematical expressions
[ 11 ]
Getting Familiar with the Spring Framework
[ 12 ]
Chapter 1
OXM JMS
Web Portlet
Transactions
Core Container
Test
After visiting the Packt Publishing website, you can search books by the author's
name or different criteria. We'll look at the service that lists books by author.
[ 13 ]
Getting Familiar with the Spring Framework
for(Book aBook:bookFinder.findAll()){
for(String anAuthor:aBook.getAuthors()){
if(anAuthor.equals(author)){
books.add(aBook);
break;
}
}
}
return books;
}
[ 14 ]
Chapter 1
To refactor this tight coupling, we can move the BookService instantiation to the
constructor of the class. The following is the modified BookLister class:
public class BookLister {
for(Book aBook:bookFinder.findAll()){
for(String anAuthor:aBook.getAuthors()){
if(anAuthor.equals(author)){
books.add(aBook);
break;
}
}
}
return books;
}
• Constructor injection
• Setter injection
[ 15 ]
Getting Familiar with the Spring Framework
The setter injection is carried out by setting a property. In a setter injection, instead
of passing bookService as a constructor argument, we change the class to pass as
a setter method argument.
The Spring IoC container is known as ApplicationContext. The objects that are
used in our application, defined in ApplicationContext, and managed by the
Spring IoC container are called beans; for example, bookService is a bean.
A bean is an object that is managed by the Spring IoC container; beans are created
with the configuration metadata that you supply to the container, such as in the
form of XML <bean/> definitions or using Java annotations.
A bean definition describes a bean instance. The bean definition contains the
information called configuration metadata, which is needed by the container to know
how to create the bean, the life cycle of the bean, and the dependencies of the bean.
[ 16 ]
Chapter 1
• class: This is mandatory and provides the fully qualified bean class name
required for the container to create the bean instance.
• name: This attribute (also known as id) uniquely identifies a bean.
• scope: This provides the scope of the objects created from a bean definition,
such as prototype and singleton. We'll learn about them later.
• constructor-arg: This injects a dependency as a bean's constructor argument.
• properties: This injects a dependency as a setter method argument.
• lazy-init: If this is set as true, the IoC container creates the bean
instance when it is first requested, rather than at startup, which means any
configuration error is not discovered until the bean is eventually instantiated
inside the Spring context.
• init-method: This provides the method name of the bean that is being
invoked just after all necessary properties on the bean are set by the IoC
container. This is useful when we need to initialize/compute something
after the bean is instantiated.
• destroy-method: The container calls this method when the bean is
destroyed; this is necessary when we need to clean up something
before the bean is destroyed.
• singleton: A single instance of the bean per IoC container. This is not
actually the same as in the singleton design pattern (that is, one instance
per classloader).
• prototype: A single bean definition to have any number of object instances.
A new bean instance is created each time one is needed.
• request: A bean instance per HTTP request, only valid in the web-aware
application context.
• session: A bean instance per HTTP session, only valid in the web-aware
application context.
• global-session: A bean instance per global HTTP session, only valid in the
web-aware application context.
[ 17 ]
Getting Familiar with the Spring Framework
1. The first step is to find and instantiate the beans. The Spring IoC container
reads the bean definitions from the XML and then instantiates them.
2. The next step is to populate the bean properties and satisfy the dependencies.
The IoC container uses dependency injection to set the properties.
3. After setting the dependencies, the setBeanName method is invoked on the
beans; if they implement the BeanNameAware interface, the setBeanName()
method is invoked by passing the ID of the bean.
4. After this, if a bean implements the BeanFactoryAware interface, the
setBeanFactory() method is called with an instance of itself.
5. The pre-initialization of BeanPostProcessor is done. If a bean
has any BeanPostProcessor interface associated with it, the
processBeforeInitialization() methods are called on the post processors.
6. The init method is called; if a bean specifies an init-method, it will be called.
7. Finally, the post-initialization is done; if there are any BeanPostProcessors
associated with the bean, their postProcessAfterInitialization()
methods are invoked.
To learn more about DI and IoC, visit the Martin Fowler site at
http://martinfowler.com/articles/injection.html.
[ 18 ]
Other documents randomly have
different content
CHAPTER XI.
EXPLORATIONS IN THE WEST INDIES.
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
textbookfull.com