Book Image

Mockito for Spring

By : Sujoy Acharya
Book Image

Mockito for Spring

By: Sujoy Acharya

Overview of this book

Table of Contents (12 chapters)
Mockito for Spring
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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.

I have taken a hands-on approach here by combining theories with examples to explain the topics.

What this book covers

Chapter 1, Getting Familiar with the Spring Framework, covers the basics of Spring, Spring projects, and especially the Spring Framework. It explores the Spring container, the life cycle of beans, dependency injection, AOP, Spring MVC, and Spring transaction management.

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.

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.

What you need for this book

You will need the following software installed before you run the examples:

Who this book is for

This book is for advanced and novice-level software testers/developers using the Spring Framework, Mockito, and JUnit. You should have a reasonable amount of knowledge and understanding of unit testing elements and applications.

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."

A block of code is set as follows:

  @Test
  public void currencyRoundsOff() throws Exception {
    assertNotNull(CurrencyFormatter.format(100.999));
    assertTrue(CurrencyFormatter.format(100.999).
      contains("$"));
    assertEquals("$101.00", CurrencyFormatter.format(100.999));
  }

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);
  }
  @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."

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

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.

To send us general feedback, simply send an e-mail to , and mention the book title via the subject of your message.

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.

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

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.

Please contact us at with a link to the suspected pirated material.

We appreciate your help in protecting our authors, and our ability to bring you valuable content.

Questions

You can contact us at if you are having a problem with any aspect of the book, and we will do our best to address it.