You are on page 1of 7

Combination of the Mockito Framework with JUnit

Faustino Paulo Muetunda


Department of Computer Engineering
Universidade da Beira Interior
Covilhã, Portugal
email address:
faustino.muetunda@ubi.pt

Abstract—This report is integrated in the Software Quality JUnit is a unit testing framework for Java programming
subject, which consists in the realization of a work aimed at the language. It plays a crucial role test-driven development and
implementation of a technology or tool in the context of is a family of unit testing frameworks collectively known as
Software Quality. From the topics guided by the Professor, I will xUnit.
have as subject to develop "Explore the combination of the
Mockito framework with JUnit", where from this composition JUnit promotes the idea of "first testing then coding",
I'll discuss unit tests, JUnit as well as its main functions, I will which emphasizes on setting up the test data for a piece of
also deal with Test Driven Development, Data Builders, make a code that can be tested first and then implemented. This
brief analysis of the coverage of the code and later, I'll address approach is like "test a little, code a little, test a little, code a
the Mocks, in this assignment, we will see how to dominate and little." It increases the productivity of the programmer and the
how entities should behave to reflect the scenario we want to test stability of program code, which in turn reduces the stress on
and also how to check if the interactions classes with these the programmer and the time spent on debugging.
entities are working as expected.
Mocking is a way to test the functionality of a class in
Finally, I will introduce a tool similar to Mockito which is isolation. Mocking does not require a database connection or
Power Mockito. The latter being more powerful and a tool that properties file read or file server read to test a functionality.
requires greater care. With it, we'll see: How can we overcome Mock objects do the mocking of the real service. A mock
Mockito’s limitations and how the two tools can work together. object returns a dummy data corresponding to some dummy
input passed to it.
Keywords—unit test, Junit, Mockito, test driven Development,
Data Builders and power Mockito. II. UNIT TESTING
I. INTRODUCTION (HEADING 1) A. Unit Testing Techniques
The simplest and quickest initial way to automate the UNIT TESTING, also known as COMPONENT
testing of our code is precisely with the use of unit tests.Junit's TESTING, is a level of software testing where individual
approach, first goes through a knowledge about unitary units / components of a software are tested. The purpose is to
testing. UNIT TESTING is a type of software testing where validate that each unit of the software performs as designed.
individual units or components of a software are tested. The The Unit Testing Techniques are mainly categorized into three
purpose is to validate that each unit of the software code parts which are Black box testing that involves testing of user
performs as expected. Unit Testing is done during the interface along with input and output, White box testing that
development (coding phase) of an application by the involves testing the functional behaviour of the software
developers. Unit Tests isolate a section of code and verify its application and Gray box testing(combination of white-box
correctness. A unit may be an individual function, method, testing and black-box testing) that is used to execute test
procedure, module, or object. In SDLC, STLC, V Model, Unit suites, test methods, test cases and performing risk analysis.
testing is first level of testing done before integration testing. Code coverage techniques used in Unit Testing are listed
Unit testing is a Whitebox testing technique that is usually below:
performed by the developer. Though, in a practical world due
to time crunch or reluctance of developers to tests, QA • Statement Coverage
engineers also do unit testing.
• Decision Coverage
• Branch Coverage
Unit Testing is important because software developers
sometimes try saving time doing minimal unit testing and this • Condition Coverage
is myth because inappropriate unit testing leads to high cost • Finite State Machine Coverage
Defect fixing during System Testing, Integration Testing and
even Beta Testing after application is built. If proper unit B. Unit Testing Example: Mock Objects
testing is done in early development, then it saves time and Unit testing relies on mock objects being created to test
money in the end. sections of code that are not yet part of a complete application.
Here, are the key reasons to perform unit testing: Unit Mock objects fill in for the missing parts of the program.
testing -> Integration testing -> System testing -> Acceptance For example, you might have a function that needs
Testing. variables or objects that are not created yet. In unit testing,
those will be accounted for in the form of mock objects created

Covilhã, Portugal 2020


solely for the purpose of the unit testing done on that section Test Package:
of code. https://github.com/FaustinoMuetunda/Aluguel_De_Filmes/t
There are several automated tools available to assist with ree/master/src/test/java
unit testing. I'll provide a few examples below:
• Junit: Junit is a free to use testing tool used for IV. JUNIT
Java programming language. It provides JUnit is a unit testing framework for Java programming
assertions to identify test method. This tool test language. It plays a crucial role test-driven development, and
data first and then inserted in the piece of code. is a family of unit testing frameworks collectively known as
• NUnit: NUnit is widely used unit-testing xUnit.
framework use for all .net languages. It is an JUnit promotes the idea of "first testing then coding",
open source tool which allows writing scripts which emphasizes on setting up the test data for a piece of
manually. It supports data-driven tests which can code that can be tested first and then implemented. This
run in parallel. approach is like "test a little, code a little, test a little, code a
little." It increases the productivity of the programmer and the
• JMockit: JMockit is open source Unit testing
stability of program code, which in turn reduces the stress on
tool. It is a code coverage tool with line and path
the programmer and the time spent on debugging.
metrics. It allows mocking API with recording
and verification syntax. This tool offers Line The xUnit architecture has these common components:
coverage, Path Coverage, and Data Coverage.
• Test case / Test suites;
• EMMA: EMMA is an open-source toolkit for
analyzing and reporting code written in Java • Test fixture;
language. Emma support coverage types like • Test runner;
method, line, basic block. It is Java-based so it is
without external library dependencies and can • Test result formatter;
access the source code.
• Assertions.
• PHPUnit: PHPUnit is a unit testing tool for PHP
A. Implementation and Tests
programmer. It takes small portions of code
which is called units and test each of them In this work, we will be using Eclip as a development IDE.
separately. The tool also allows developers to For the use of JUnit, we first need to download the
use pre-define assertion methods to assert that a dependencies, as shown in the image below:
system behave in a certain manner.
III. DEVELOPMENT SCENE
A movie allocator charges one amount per working
day (including Saturday). However, if the film is rented on
Saturday, it will have to be returned on Monday. The same,
has the following conditions of promotion: If the customer
rents 3 films, for the third party will pay only 25% of the
value of this film. When renting 4, you will have a 50%
discount of the value in the fourth film. When renting 5, you
will have a 75% discount on the value in the fifth film and
When renting 6, you will have a 100% discount of the value The performance of this work followed three steps:
in the sixth film. Scenario: Where all the initial configuration is performed so
Access to promotions, there will also be other that the scene, we want to test is available.
restrictions and care: Must rent film the system will have Action: Where the meth we want to test, will be effectively
access to the Criminal History Certificate of the client. In case executed.
you were positive in your criminal record history, you will Verification: I delete the execution results, the
not benefit from the discounts. It should address errors (Since action over3 the input environment expecified and this result
the information is external); The Program must not rent films can be an object, success message, error, failure or even an
that do not exist in stock; You must not allow you to rent attribute.
movies without a User; You must send email for rent in First, all we have to use @Test to JUnit recognizes as a test
arrears; Must return on the second if it is rented on Saturday; meth:
Future complexities could be added throughout the
development of this report.
All code, implementation and development history can be
accessed:
Main Package:
https://github.com/FaustinoMuetunda/Aluguel_De_Filmes/t
ree/master/src/main/java
V. TEST DRIVEN DEVELOPMENT
Test Driven Development (TDD) is software development
approach in which test cases are developed to specify and
validate what the code will do. In simple terms, test cases for
each functionality are created and tested first and if the test
fails then the new code is written in order to pass the test and
making code simple and bug-free.
Test-Driven Development starts with designing and
developing tests for every small functionality of an
application. TDD instructs developers to write new code only
This is an example of a scenario where: However, if if an automated test has failed. This avoids duplication of
the film is rented on Saturday, it will have to be returned on code. The full form of TDD is Test-driven development.
Monday.

Now, we're going to introduce an failures in the code


to see how our test behaves:

Execution Suite
Because our tests are in more than one class, it's interesting
We see that it has emitted a failures and bar turned to have a way to run them all in just a single test battery. For
this, I will create the suites package, where you will have the
red, this happens, when there is an error or failures and it is
execution suite. JUnit, recognize the execution class when we
only possible, thanks to the assertions of Junit. Making it easy
use the @RunWith (Suite.class)
to see errors and failures. If everything is compliant, the bar
will keep it green.
The failure was to have introduced a different day
than Monday.

As a matter of organization, it's interesting to


separate the test methods from the class we're testing. To
facilitate test tracing, I will adopt the test convention for each
class I will be testing, and the class name will be the same
plus the test suffix.

VI. DATA BUILDERS


Managing test data in unit tests is not an easy job. If you
don’t find a good solution, you end up with plenty of
boilerplate code that is hard to read and understand, hard to
maintain. On the other hand there is not silver bullet solution
for that problem. I experimented with many approaches.
Depending on the size of the problem I need to deal with I
select a different approach, sometimes combining multiple
approaches in one project.
For this case, I created the builders package, where I make
a builder for each class: FilmeBuider, LocacaoBuider and
UsuárioBuilder.
As the following images show:
For this example, I will demonstrate the case of
FilmeBuider.
Our evaluation is made for our main package and not
necessarily for our test batteries.
For this example, I will demonstrate the case of
FilmeBuider.

In the figure of the percentage of acceptance of the code,


we see the green lines that symbolizes that the code was
executed completely, the yellow line indicates that it was
executed partially and red only occurs in situations that
For more examples about builders you can found: contain logic i.e., execution can take different(As the case of
the conditions applied for Saturdays).
https://github.com/FaustinoMuetunda/Aluguel_De_Filmes/tr
ee/master/src/test/java/builders These different colour lines followed are also known as
branches
Coverage analysis:
Test Coverage, on the other hand, is testing every
Simply put, coverage is “What are we testing and How requirement at least once and is obviously a QA team activity.
much are we testing?”
General Coverage Test:
Test coverage helps monitor the quality of testing and
assists testers to create tests that cover areas that are missing
or not validated.
Most teams base their coverage calculations on functional
requirements alone. It is also fair because first and foremost
an application should do what it is supposed to do. If not, its
speed or security or ease of use – none of it matters.
However, if dedicated and independent non-functional
testing teams are working on performance, security, usability Specific coverage tests:
testing, etc., then they will have to track their requirements all
the way to execution through test coverage analytics.
Test Coverage and Code Coverage
Test coverage is often confused with Code Coverage.
Even though the underlying principles are the same, they are
two different things.
Code Coverage really talks about unit testing practices that
must target all areas of the code at least once and is done by
developers.
From our scene, this is the percentage of Code coverage:
What really qualifies to be a covered requirement depends In our code, because the JUnit does not deal with external
on the interpretation of each team. dependencies, we need mocks to deal with this limitation.
Conclusion From this we create the injection of mocks in all service
classes (Which deal with these dependencies):
Test coverage does not end with the mentioned contexts.
There are many other points that should be considered when
it comes to testing coverage.
It is not always true that when you test more, the results
are better. In fact, when you test more with no apparent
strategy, you probably will end up investing a lot of time.
With a more structured approach, an aim at 100% requirement
coverage and effective testing methods, you will not
compromise on quality.
VII. MOCKITO
Mocking is a way to test the functionality of a class in Because we are dealing with external dependencies linked
isolation. Mocking does not require a database connection or to the criminal record, in the main class we have created a
properties file read or file server read to test a functionality. class that handles this access which is the SPCService.
Mock objects do the mocking of the real service. A mock
object returns a dummy data corresponding to some dummy
input passed to it.
Mockito facilitates creating mock objects seamlessly. It
uses Java Reflection in order to create mock objects for a
given interface. Mock objects are nothing but proxy for actual
implementations.
Consider a case of Stock Service which returns the price
details of a stock. During development, the actual stock When you create your test, in the test suite, we create the
service cannot be used to get real-time data. So we need a public method naoDeveAlugarParaNegativadoSPC(). It uses
dummy implementation of the stock service. Mockito can do the robust form to create a JUnit test, preventing false
the same very easily, as its name suggests. positives from existing.
Benefits of Mockito:
• No Handwriting − No need to write mock objects
on your own.
• Refactoring Safe − Renaming interface method
names or reordering parameters will not break
the test code as Mocks are created at runtime.
• Return value support − Supports return values.
• Exception support − Supports exceptions.
• Order check support − Supports check on order
of method calls.
• Annotation support − Supports creating mocks
using annotation. I refactored the code and added for all the method that have
external dependencies.
To use mockito, we first need to create your dependencies,
artifacts as well as define your version:
https://github.com/FaustinoMuetunda/Aluguel_De_Filme
s/blob/master/src/test/java/servicoss/LocacaoServiceTeste.ja
va (For more examples of implementing the).

VIII. POWER MOCKITO


Mockito is a powerful, open-source Mocking framework
in Java. The features it provides for unit-testing is inevitably
unique and important, nonetheless, ease out a lot of work for
developers while writing unit test cases.
While Mockito can help with virtually everything, there
are some things it cannot do. Like stubbing or testing private,
final or static methods. It needs much more power to write test
cases for such methods which usually causes developers to
write cumbersome code for these methods.
Here, PowerMockito comes to the rescue. PowerMockito In this way, we have all our test stacks
is a PowerMock's extension API to support Mockito. It running successfully.
provides capabilities to work with the Java Reflection API in
a simple way to overcome the problems of Mockito, such as
the lack of ability to mock final, static or private methods. IX. CONCLUSION
Preparing for Testing With PowerMockito Although unit testing is a proven technique for ensuring
software quality, it’s still considered a burden to developers
The first step to integrate PowerMock support for
and many teams are still struggling with it. In order to get the
Mockito is to include the following two dependencies in the
most out of testing and automated testing tools, tests must be
Maven POM file: trustworthy, maintainable, readable, self-contained, and be
used to verify a single use case. Automation is key to making
unit testing workable and scalable.
In addition, software teams need to practice good testing
techniques, such as writing and reviewing tests alongside
application code, maintaining tests, and ensuring that failed
tests are tracked and remediated immediately. Adopting these
unit testing best practices can quickly improve your unit
testing outcomes.
Next, we need to prepare our test cases for working with
PowerMockito by applying the following two annotations: JUnit is a unit testing framework for Java programming
language. It´s has been important in the development of test-
@RunWith(PowerMockRunner.class) driven development, and is one of a family of unit testing
@PrepareForTest(LocacaoService.class) frameworks collectively known as xUnit, that originated with
JUnit.
The LocacaoService element in the @PrepareForTest The combination of the JUnit framework and mockito
annotation represents an array of fully qualified names of produces a very complementary result in the treatment of tests
types we want to mock. and their dependency. It is always recommended to use
Now we are ready to exploit the power of PowerMockito. powerMockito, to complement, all the limitations present in
Since the beginning of our program we had the case that JUnit and Mockito.
the test only took place on Saturday, because it has a unique
condition which categorical a limitation, both for junit and
mockito. Now, using PowerMock, we'll see how this REFERENCES
limitation can be resolved.
First, we had to change the [1] https://www.parasoft.com/unit-testing-best-practices-getting-the-
Assume.assumeTrue(DataUtils.verificarDiaSemana(n most-out-of-your-test-automation
ew Date(), Calendar.SATURDAY)); which was used simply [2] https://www.guru99.com/test-driven-development.htmlK.
to allow you to deal with this contract clause and add the [3] https://www.guru99.com/test-driven-development.html
PowerMockito.whenNew(Date.class).withNoArguments().t [4] Test Coverage In Software Testing (Tips To Maximize Testing
henReturn(DataUtils.obterData(16, 1, 2021)); that will be Coverage. Access: https://www.softwaretestinghelp.com/test-
coverage/
rewriting an external meth of our class package.
[5] PowerMock tutorial Acess https://java2blog.com/powermock-tutorial/
[6] Wagner Costa, Testes Unitários em Java, curse in Udemy
[7] https://java2blog.com/powermock-tutorial/
[8] https://www.parasoft.com/unit-testing-best-practices-getting-the-
most-out-of-your-test-automation
TABLE ANNOTATIONS
import org.junit.jupiter.api.* Import statement for using the following annotations.
@Test Identifies a method as a test method.
@RepeatedTest(<Number>) Repeats the test a <Number> of times
@TestFactory Method is a Factory for dynamic tests
@BeforeEach Executed before each test. It is used to prepare the test
environment (e.g., read input data, initialize the class).
@BeforeAll Executed once, before the start of all tests. It is used to
perform time intensive activities, for example, to connect to
a database. Methods marked with this annotation need to be
defined as static to work with JUnit.
@AfterAll Executed once, after all tests have been finished. It is used
to perform clean-up activities, for example, to disconnect
from a database. Methods annotated with this annotation
need to be defined as static to work with JUnit.
@Nested Let’s you nest inner test classes to force a certain execution
order
@Tag("<TagName>") Tests in JUnit 5 can be filtered by tag. E.g., run only tests
tagged with "fast".
@ExtendWith Let’s you register an Extension class that integrates with
one or more extension points.
@Disabled or @Disabled("Why disabled") Marks that the test should be disabled. This is useful when
the underlying code has been changed and the test case has
not yet been adapted. Or if the execution time of this test is
too long to be included. It is best practice to provide the
optional description, why the test is disabled.
@DisplayName("<Name>") <Name> that will be displayed by the test runner. In
contrast to method names the DisplayName can contain
spaces.
@Test (expected = Exception.class) Fails if the method does not throw the named exception.
@Test(timeout=100) Fails if the method takes longer than 100 milliseconds.

You might also like