Testing Applications with JUnit5 and EasyMock. Part 2

JUnit best practices: EasyMock object creation

  • We open an HTTP connection (1)
  • We read all the content that is received (2)
  • If an error occurs, we return null (3)
  1. We start by importing the objects that we need (1). Notice that because we use the class extensions of EasyMock, we now need to import the org.easymock.classextension.EasyMock object instead of org.easymock.EasyMock. Now we’re ready to create mock objects of classes and interfaces using the statically imported methods of the class extensions.
  2. In (2), as in the previous listings, we declare the objects which we want to mock, and in (3) we call the createMock method to initialize them.
  3. In (4) we define the expectation of the stream when the read method is invoked (notice that to stop reading from the stream, the last thing to return is a -1). Working with a low-level stream, we define how to read one byte at a time, as InputStream is reading byte by byte. In (5) we expect the close method to be called on the stream.
  4. Now we need to denote that we’re done by declaring our expectations — we do this by calling the replay method (6). The replay method is used to pass the mock from the phase where we record the method we expect to be called, to where we test. Before this, we recorded the behavior, but the object isn’t working as a mock. After calling replay, it works as expected. The rest is invoking the method under test (7), and asserting the expected result (8).
  1. We define an expectation where we expect the close method of the stream to be invoked (9).
  2. Right on the next line we declare that an IOException should be raised if this call occurs (10).






Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

The 2 Week Process to learning AWS and System Design.

How To Install and Use Composer on Debian 9

SVG: The Web Graphic Language

CS373 Fall 2020: Elias Lampietti

Getting started with OutSystems and Microsoft Graph — Delegated Permissions

Database Setup with DbUp + Postgresql + Dapper in ASP.Net Core

WORKPRO 164PC Tool Set Socket Wrench Set Hand Tools for Car Repair Set of Tool Instruments Sockets…

Tutorial ESP32 Door Lock 3in1 Fingerprint Keypad 4x3 and RFID PN532

Tutorial ESP32 Door Lock 3in1 Fingerprint Keypad 4x3 and RFID PN532

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Luxoft Training

Luxoft Training


More from Medium

Checking performance of different SSL/TLS implementations for Java Applications

Authorisation with Spring Security — Part 2

Reflection API

Reentrant lock in Java.