Testing Applications with JUnit5 and EasyMock. Part 2

JUnit best practices: EasyMock object creation

Here’s a nice-to-know tip on the createMock method. If you check the API of EasyMock you see that the createMock method comes with numerous signatures. The signature that we use is:

  • 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).

Conclusions

This article has demonstrated the steps needed to test a Java application with the help of JUnit 5 and EasyMock. We showed how to test the functionality of an AccountService by mocking an AccountManager and of a WebClient by mocking a ConnectionFactory and an InputStream.

--

--

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