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

Part 1: An easy way to automatically manage the AWS SG with Terraform and Python…

KDE Plasma 5.20 is finally available for Feren OS!

A Gentle Beginner Introduction To Numpy Arrays

Analyze Large CSV Files in Minutes With Docker Compose

Community Creates Resources, Tools for Staking and Earning KEEP

Memory management in Python

Build a Paint App with es6 in 10 minutes!

AWS Managed Streaming for Apache Kafka : Streaming messages from producer to consumer using Amazon…

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

[Spring Boot] Testing Apache Camel SEDA Endpoint

Object-relational Mapping Using JPA, Hibernate and Spring Data JPA.

Circuit Breaker And Retry with Spring Cloud Resiliance4j

Writing a Logging Aspect with Spring AOP