This article may be too technical for most readers to understand.(February 2010) |
Developer(s) | Szczepan Faber, Brice Dutheil, Rafael Winterhalter, Tim van der Lippe and others. |
---|---|
Stable release | 5.4.0 / June 18, 2023 [1] |
Repository | github |
Written in | Java |
Type | Testing |
License | MIT License [2] |
Website | site |
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).
The framework's name and logo are a play on mojitos, a type of drink.
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]
Mockito began by expanding on the syntax and functionality of EasyMock. [9] [10]
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.
JUnit is a test automation framework for the Java programming language. JUnit is often used for unit testing, and is one of the xUnit frameworks.
In computer programming, lazy initialization is the tactic of delaying the creation of an object, the calculation of a value, or some other expensive process until the first time it is needed. It is a kind of lazy evaluation that refers specifically to the instantiation of objects or other resources.
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 in the programming language ML in 1973, permits writing common functions or data 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 instances of 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.
Unit testing, a.k.a. component or module testing, is a form of software testing by which isolated source code is tested to validate expected behavior.
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.
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.
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.
In software engineering, dependency injection is a programming technique in which an object or function receives other objects or functions that it requires, as opposed to creating them internally. 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 that 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 Cedric_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.
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.
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 software engineering, a fluent interface is an object-oriented API whose design relies extensively on method chaining. Its goal is to increase code legibility by creating a domain-specific language (DSL). The term was coined in 2005 by Eric Evans and Martin Fowler.
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".
Nemerle is a general-purpose, high-level, statically typed programming language designed for platforms using the Common Language Infrastructure (.NET/Mono). It offers functional, object-oriented, aspect-oriented, reflective and imperative features. It has a simple C#-like syntax and a powerful metaprogramming system.
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, or Google Gson, is an open-source Java library that serializes Java objects to JSON.
Castor is a data binding framework for Java with some features like Java to Java-to-XML binding, Java-to-SQL persistence, paths between Java objects, XML documents, relational tables, etc. Castor is one of the oldest data binding projects.