Mockito

Last updated
Mockito
Developer(s) Szczepan Faber, Brice Dutheil, Rafael Winterhalter, Tim van der Lippe and others.
Stable release
5.4.0 / June 18, 2023;39 days ago (2023-06-18) [1]
Repository github.com/mockito/mockito
Written in Java
Type Testing
License MIT License [2]
Website site.mockito.org

Mockito is an open source testing framework for Java released under the MIT License. [3] [4] The framework allows the creation of test double objects (mock objects) in automated unit tests for the purpose of test-driven development (TDD) or behavior-driven development (BDD).

Contents

The framework's name and logo are a play on mojitos, a type of drink.

Features

Mockito allows developers to verify the behavior of the system under test (SUT) without establishing expectations beforehand. [5] One of the criticisms of mock objects is that there is a tight coupling of the test code to the system under test. [6] Mockito attempts to eliminate the expect-run-verify pattern [7] by removing the specification of expectations. Mockito also provides some annotations for reducing boilerplate code. [8]

Origins

Mockito began by expanding on the syntax and functionality of EasyMock. [9] [10]

Example

Consider this decoupled Hello world program; we may unit test some of its parts, using mock objects for other parts.

packageorg.examples;importjava.io.IOException;publicclassHelloApplication{publicstaticinterfaceGreeter{StringgetGreeting(Stringsubject);StringgetIntroduction(Stringactor);}publicstaticclassHelloGreeterimplementsGreeter{privateStringhello;privateStringsegmenter;publicHelloGreeter(Stringhello,Stringsegmenter){this.hello=hello;this.segmenter=segmenter;}publicStringgetGreeting(Stringsubject){returnhello+" "+subject;}publicStringgetIntroduction(Stringactor){returnactor+segmenter;}}publicstaticinterfaceHelloActable{voidsayHello(Stringactor,Stringsubject)throwsIOException;}publicstaticclassHelloActionimplementsHelloActable{privateGreeterhelloGreeter;privateAppendablehelloWriter;publicHelloAction(GreeterhelloGreeter,AppendablehelloWriter){super();this.helloGreeter=helloGreeter;this.helloWriter=helloWriter;}publicvoidsayHello(Stringactor,Stringsubject)throwsIOException{helloWriter.append(helloGreeter.getIntroduction(actor)).append(helloGreeter.getGreeting(subject));}}publicstaticvoidmain(String...args)throwsIOException{newHelloAction(newHelloGreeter("hello",": "),System.out).sayHello("application","world");}}

The result of HelloApplication launching will be the following:

application: hello world 

Unit test for HelloActable component may look like this:

packageorg.examples;import staticorg.mockito.Matchers.any;import staticorg.mockito.Matchers.eq;import staticorg.mockito.Mockito.mock;import staticorg.mockito.Mockito.times;import staticorg.mockito.Mockito.verify;import staticorg.mockito.Mockito.when;importorg.junit.Before;importorg.junit.Test;importorg.examples.HelloApplication.HelloActable;importorg.examples.HelloApplication.HelloAction;importorg.examples.HelloApplication.Greeter;publicclassHelloActionUnitTest{GreeterhelloGreeterMock;AppendablehelloWriterMock;HelloActablehelloAction;@BeforepublicvoidsetUp(){helloGreeterMock=mock(Greeter.class);helloWriterMock=mock(Appendable.class);helloAction=newHelloAction(helloGreeterMock,helloWriterMock);}@TestpublicvoidtestSayHello()throwsException{when(helloWriterMock.append(any(String.class))).thenReturn(helloWriterMock);when(helloGreeterMock.getIntroduction(eq("unitTest"))).thenReturn("unitTest : ");when(helloGreeterMock.getGreeting(eq("world"))).thenReturn("hi world");helloAction.sayHello("unitTest","world");verify(helloGreeterMock).getIntroduction(eq("unitTest"));verify(helloGreeterMock).getGreeting(eq("world"));verify(helloWriterMock,times(2)).append(any(String.class));verify(helloWriterMock,times(1)).append(eq("unitTest : "));verify(helloWriterMock,times(1)).append(eq("hi world"));}}

It uses mock objects for the Greeter and Appendable interfaces, and implicitly assumes the next use case:

unitTest : hi world 

Integration test code for testing HelloActable wired together with Greeter may look like the following:

packageorg.examples;import staticorg.mockito.Matchers.any;import staticorg.mockito.Matchers.eq;import staticorg.mockito.Mockito.mock;import staticorg.mockito.Mockito.times;import staticorg.mockito.Mockito.verify;import staticorg.mockito.Mockito.when;importorg.junit.Before;importorg.junit.Test;importorg.examples.HelloApplication.HelloActable;importorg.examples.HelloApplication.HelloAction;importorg.examples.HelloApplication.Greeter;importorg.examples.HelloApplication.HelloGreeter;publicclassHelloActionIntegrationTest{HelloActablehelloAction;GreeterhelloGreeter;AppendablehelloWriterMock;@BeforepublicvoidsetUp(){helloGreeter=newHelloGreeter("welcome"," says ");helloWriterMock=mock(Appendable.class);helloAction=newHelloAction(helloGreeter,helloWriterMock);}@TestpublicvoidtestSayHello()throwsException{when(helloWriterMock.append(any(String.class))).thenReturn(helloWriterMock);helloAction.sayHello("integrationTest","universe");verify(helloWriterMock,times(2)).append(any(String.class));verify(helloWriterMock,times(1)).append(eq("integrationTest says "));verify(helloWriterMock,times(1)).append(eq("welcome universe"));}}

It uses mock objects only in place of Appendable interfaces, uses the real implementations for other (HelloActable and Greeter) interfaces, and implicitly assumes the next use case:

integrationTest says welcome universe 

As can be seen from the import statements of HelloActionUnitTest and HelloActionIntegrationTest classes, it is necessary to put some Mockito jars and JUnit jars in your class path to be able to compile and run the test classes.

See also

Related Research Articles

JUnit is a unit testing framework for the Java programming language. JUnit has been important in the development of test-driven development, and is one of a family of unit testing frameworks which is collectively known as xUnit that originated with SUnit.

Generic programming is a style of computer programming in which algorithms are written in terms of data types to-be-specified-later that are then instantiated when needed for specific types provided as parameters. This approach, pioneered by the ML programming language in 1973, permits writing common functions or types that differ only in the set of types on which they operate when used, thus reducing duplicate code.

In object-oriented programming, the decorator pattern is a design pattern that allows behavior to be added to an individual object, dynamically, without affecting the behavior of other objects from the same class. The decorator pattern is often useful for adhering to the Single Responsibility Principle, as it allows functionality to be divided between classes with unique areas of concern as well as to the Open-Closed Principle, by allowing the functionality of a class to be extended without being modified. Decorator use can be more efficient than subclassing, because an object's behavior can be augmented without defining an entirely new object.

In computer programming, unit testing is a software testing method by which individual units of source code—sets of one or more computer program modules together with associated control data, usage procedures, and operating procedures—are tested to determine whether they are fit for use.

<span class="mw-page-title-main">Swing (Java)</span> Java-based GUI toolkit

Swing is a GUI widget toolkit for Java. It is part of Oracle's Java Foundation Classes (JFC) – an API for providing a graphical user interface (GUI) for Java programs.

In computer science, reflective programming or reflection is the ability of a process to examine, introspect, and modify its own structure and behavior.

<span class="mw-page-title-main">NUnit</span>

NUnit is an open-source unit testing framework for the .NET Framework and Mono. It serves the same purpose as JUnit does in the Java world, and is one of many programs in the xUnit family.

<span class="mw-page-title-main">Java syntax</span> Set of rules defining correctly structured program

The syntax of Java is the set of rules defining how a Java program is written and interpreted.

EGL, originally developed by IBM and now available as the EDT open source project under the Eclipse Public License (EPL), is a programming technology designed to meet the challenges of modern, multi-platform application development by providing a common language and programming model across languages, frameworks, and runtime platforms.

<span class="mw-page-title-main">Dependency injection</span> Software programming technique

In software engineering, dependency injection is a programming technique in which an object or function receives other objects or functions that it depends on. Dependency injection aims to separate the concerns of constructing objects and using them, leading to loosely coupled programs. The pattern ensures that an object or function which wants to use a given service should not have to know how to construct those services. Instead, the receiving 'client' is provided with its dependencies by external code, which it is not aware of. Dependency injection makes implicit dependencies explicit and helps solve the following problems:

In computer programming, an entry point is the place in a program where the execution of a program begins, and where the program has access to command line arguments.

TestNG is a testing framework for the Java programming language created by Cédric Beust and inspired by JUnit and NUnit. The design goal of TestNG is to cover a wider range of test categories: unit, functional, end-to-end, integration, etc., with more powerful and easy-to-use functionalities.

In software engineering, behavior-driven development (BDD) is a software development process that gels well with agile software development process that encourages collaboration among developers, quality assurance experts, and customer representatives in a software project. It encourages teams to use conversation and concrete examples to formalize a shared understanding of how the application should behave. It emerged from test-driven development (TDD). Behavior-driven development combines the general techniques and principles of TDD with ideas from domain-driven design and object-oriented analysis and design to provide software development and management teams with shared tools and a shared process to collaborate on software development.

Selenium is an open source umbrella project for a range of tools and libraries aimed at supporting browser automation. It provides a playback tool for authoring functional tests across most modern web browsers, without the need to learn a test scripting language. It also provides a test domain-specific language (Selenese) to write tests in a number of popular programming languages, including JavaScript (Node.js), C#, Groovy, Java, Perl, PHP, Python, Ruby and Scala. Selenium runs on Windows, Linux, and macOS. It is open-source software released under the Apache License 2.0.

Jakarta Mail is a Jakarta EE API used to send and receive email via SMTP, POP3 and IMAP. Jakarta Mail is built into the Jakarta EE platform, but also provides an optional package for use in Java SE.

Stripes is an open source web application framework based on the model–view–controller (MVC) pattern. It aims to be a lighter weight framework than Struts by using Java technologies such as annotations and generics that were introduced in Java 1.5, to achieve "convention over configuration". This emphasizes the idea that a set of simple conventions used throughout the framework reduce configuration overhead. In practice, this means that Stripe applications barely need any configuration files, thus reducing development and maintenance work. It has been dormant since 2016.

In object-oriented computer programming, a null object is an object with no referenced value or with defined neutral (null) behavior. The null object design pattern, which describes the uses of such objects and their behavior, was first published as "Void Value" and later in the Pattern Languages of Program Design book series as "Null Object".

Concordion is a specification by example framework originally developed by David Peterson, and now maintained by a team of contributors, led by Nigel Charman.

Gson is an open-source Java library to serialize and deserialize Java objects to JSON.

EasyMock is an open-source testing framework for Java released under the Apache License. The framework allows the creation of test double objects for the purpose of Test-driven Development (TDD) or Behavior Driven Development (BDD).

References

  1. "Project Releases Overview on GitHub". GitHub . Retrieved 29 April 2022.
  2. "License · mockito/mockito Wiki · GitHub". GitHub . Retrieved 30 August 2019.
  3. "Mockito in six easy examples". 2009. Retrieved 2012-10-05.
  4. "What's the best mock framework for Java?" . Retrieved 2010-12-29.
  5. "Features and Motivations" . Retrieved 2010-12-29.
  6. Fowler, Martin (2007). "Mocks Aren't Stubs" . Retrieved 2010-12-29.
  7. Faber, Szczepan. "Death Wish" . Retrieved 2010-12-29.
  8. Kaczanowski, Tomek. "Mockito - Open Source Java Mocking Framework" . Retrieved 2013-09-17.
  9. Faber, Szczepan. "Mockito". Archived from the original on 2010-03-29. Retrieved 2010-12-29.
  10. "Mockito Home Page" . Retrieved 2010-12-29.