Music is an art form whose medium is sound and silence. Generally, a song is considered the smallest standalone work of music, especially when involving singing.
Music is an art form whose medium is sound and silence. Generally, a song is considered the smallest standalone work of music, especially when involving singing.
The common elements of music are pitch (which governs melody and harmony), rhythm (and its associated concepts tempo, meter, and articulation), dynamics, and the sonic qualities of timbre and texture.
Music is an art form whose medium is sound and silence. Generally, a song is considered the smallest standalone work of music, especially when involving singing.
The common elements of music are pitch (which governs melody and harmony), rhythm (and its associated concepts tempo, meter, and articulation), dynamics, and the sonic qualities of timbre and texture. The word derives from Greek μουσική (mousike; "art of the Muses").


#include <data_flow_ops.h>
Optional attribute setters for ConditionalAccumulator.
Public attributes |
|
|---|---|
container_ = ""
|
StringPiece
|
reduction_type_ = "MEAN"
|
StringPiece
|
shared_name_ = ""
|
StringPiece
|
Public functions |
|
|---|---|
Container(StringPiece x)
|
TF_MUST_USE_RESULT Attrs
If non-empty, this accumulator is placed in the given container.
|
ReductionType(StringPiece x)
|
TF_MUST_USE_RESULT Attrs
Defaults to "MEAN".
|
SharedName(StringPiece x)
|
TF_MUST_USE_RESULT Attrs
If non-empty, this accumulator will be shared under the given name across multiple sessions.
|
StringPiece tensorflow::ops::ConditionalAccumulator::Attrs::container_ = ""
StringPiece tensorflow::ops::ConditionalAccumulator::Attrs::reduction_type_ = "MEAN"
StringPiece tensorflow::ops::ConditionalAccumulator::Attrs::shared_name_ = ""
TF_MUST_USE_RESULT Attrs tensorflow::ops::ConditionalAccumulator::Attrs::Container( StringPiece x )
If non-empty, this accumulator is placed in the given container.
Otherwise, a default container is used.
Defaults to ""
TF_MUST_USE_RESULT Attrs tensorflow::ops::ConditionalAccumulator::Attrs::ReductionType( StringPiece x )
Defaults to "MEAN".
TF_MUST_USE_RESULT Attrs tensorflow::ops::ConditionalAccumulator::Attrs::SharedName( StringPiece x )
If non-empty, this accumulator will be shared under the given name across multiple sessions.
Defaults to ""


gnmmanage
Manages networks
Synopsis
gnmmanage [--help][-q][-quiet][--long-usage]
[info]
[create [-f <format_name>] [-t_srs <srs_name>] [-dsco NAME=VALUE]... ]
[import src_dataset_name] [-l layer_name]
[connect <gfid_src> <gfid_tgt> <gfid_con> [-c <cost>] [-ic <inv_cost>] [-dir <dir>]]
[disconnect <gfid_src> <gfid_tgt> <gfid_con>]
[rule <rule_str>]
[autoconnect <tolerance>]
[delete]
[change [-bl gfid][-unbl gfid][-unblall]]
<gnm_name> [<layer> [<layer> ...]]
Description
The gnmmanage program can perform various managing operations on geographical networks in GDAL. In addition to creating and deleting networks this includes capabilities of managing network's features, topology and rules.
- -info
Different information about network: system and class layers, network metadata, network spatial reference.
- create
Create network.
- -f <format_name>
Output file format name.
- -t_srs <srs_name>
Spatial reference input.
- -dsco NAME=VALUE
Network creation option set as pair name=value.
- import <src_dataset_name>
Import layer with dataset name to copy.
- -l layer_name
Layer name in dataset. If unset, 0 layer is copied.
- connect <gfid_src> <gfid_tgt> <gfid_con>
Make a topological connection, where the gfid_src and gfid_tgt are vertices and gfid_con is edge (gfid_con can be -1, so the system edge will be inserted).
Manually assign the following values:
- -c <cost>
Cost / weight
- -ic <invcost>
Inverse cost
- -dir <dir>
Direction of the edge.
- disconnect <gfid_src> <gfid_tgt> <gfid_con>
Removes the connection from the graph.
- rule <rule_str>
Creates a rule in the network by the given rule_str string.
- autoconnect <tolerance>
Create topology automatically with the given double tolerance and layer names. In no layer name provided all layers of network will be used.
- delete
Delete network.
- change
Change blocking state of network edges or vertices.
- -bl <gfid>
Block feature before the main operation. Blocking features are saved in the special layer.
- -unbl <gfid>
Unblock feature before the main operation.
- -unblall
Unblock all blocked features before the main operation.
- <gnm_name>
The network to work with (path and name).
- <layer>
The network layer name.


Binghamton ACM
-
Who We Are
We are Binghamton University's student chapter of the Association for Computing Machinery, an international society for Computer Scientists.
-
What We Do
We host tech talks, programming competitions, and other fun events!
-
Get Involved
Have a question? Need information? Want to say hello? Whatever it is, you can reach us here!


Plan
Understand the problem, find viable paths, and set the direction.
Understand the problem, find viable paths, and set the direction.
Build a product that minimally solves the problem, get feedback from users, iterate and improve. Develop a solution using open source and free tools.
Give the project wings and breath life into it. Market the heck out of it and enjoy the success of your labors.


integrate_piecewise(function,
x,
method=' romberg ' ,
return_pieces=False,
**kwargs)
| source code
|
Integrate function and return the integral at a sequence of points.
Useful when you want to efficiently calculate a cumulative integral.
Also useful for piecewise-defined functions where discontinuities
or critical points cause quadrature routines to complain or become
inaccurate.
Integration methods available are: quad, romberg.
Parameters
- function : callable
- User defined function. Should take a single vector argument
and return q vector of the same shape.
- x : array_like
- Array of points at which to evaluate the integral.
- method : str, optional
- Name of the method to use to integrate each segment. 'quad' or
'romberg'.
- return_pieces : bool, optional
- Return the individual segments rather than the sum of all
preceding segments.
Returns
- integral : ndarray
- The value of the integral at each x. The first value is always zero.
|


Make Event
Item 1 0
Item 1 1
Item 1 2
Upload Video
Upload Photo
History
Advertisement
Chat box
Other NGO's
Inbox
Delete ID
CSS input Radio Button Css3Menu.com


JF's Notes'
Important Concepts
How the Web Works
>user
>browser
>internet cloud
>HTTP request to server
HTML: Hypertext Markup Language; contains content
and markup describes how it looks.
Computers do what they are told and take things literally. Even the smallest error
can cause problems in the program.
Elements are either inline or block.
Block elements form an "invisible box" around the content inside them.
Here are the the rest of my notes.


Coors Regular
The Molson standard brew, a cool and crisp lager that has been around for years.
Coors Non-Alcoholic
We offer a non-alcoholic brew, which tastes exactly like our Regular beer but with none of the alcohol content!
Coors Light
Coors Light is lighter-than-light, refreshing and easy to drink on a hot summer's day in the mountains.


|
mpi_cmake_modules
|
In the machines-in-motion group we use doxygen in order to build all documentations from C/C++ and Python code. The main idea is that we can have a unifyed way to generate the documentation.
In order to use this macro one obviously needs to depend on this package through a find_package
or using catkin
components. Once the dependency is found the following macro needs to be added to the CMakelists.txt:
build_doxygen_documentation()
This macro is idle by default. To activate it one need to pass the following CMake argument:
catkin build --cmake-args -DGENERATE_DOCUMENTATION=ON
The macro will generate a specific target using the name of the project for unicity. The documentation is located in:
workspace/devel/share/<project name>/doc/html/
In order to visual the built documentation with firefox please run:
firefox workspace/devel/share/<project name>/doc/html/index.html
In order to write a decent documentation one need to make sure that Doxygen do not output warnings. A warning from DOxygen proves that a code item is not documentated. See the C++ coding guidelines , the Python coding guidelines and the General coding guidelines For more information on how our code style and the good code practice.
The documentation of your code is combined with several main items:
```C++ /** * \@example <file name> This example provide an exmaple on how to use ... * Remarque: remove the `\` before the `@`. */ ```
doc/
folder containing the additionnal documentation.For more detail on how to use doxygen here is a list of extremely useful links:
The Doxyfile.in
place in this repository's resources
folder is reponsible for the parsing paramters and shape of the documentation. The idea here is that upon build Doxygen will go recursively through all the current project files looking for the C/C++/Python/Markdown files and generate the documentation automatically.
The subtility about python is that we use the doxypypy package in order to convert the Google docstring in the python code into Doxygen recognizable docstrings. So one need to install this dependency using pip for example.


{% extends "base.html" %} {% load crispy_forms_tags %} {% load i18n %} {% block title %}Add Rooms{% endblock %} {% block content %}
The Chief Ministers's office request to know information about total capacity and current Utlisation of Normal Beds, ICU Beds and Ventilators in your Hospital.
1. Normal Beds
2. ICU Beds
3. Ventilators


About
Flexible web application developer, creative and logical thinker, and passionate techie. Experience as a freelance developer as well as a quality assurance analyst/developer in a corporate environment.
Explore PlaygroundFlexible web application developer, creative and logical thinker, and passionate techie. Experience as a freelance developer as well as a quality assurance analyst/developer in a corporate environment.
Explore Playground


I'll select a random number from 0-100. Now, you have to guess that exact number. If you are getting closer to the number, you'll get hotter, if not you'll get colder. LETS PLAY!!!


ngClass directive is a attribute directive. way of using it as [ngClass]="your condition or class name".


public enum CompanyField extends java.lang.Enum<CompanyField> implements CompositeEnum<CompanyField>
| Enum Constant and Description |
|---|
BLOG_RSS_URL
A human readable name for the facet.
|
COMPANY_TYPE
A human readable name for the facet.
|
DESCRIPTION
A human readable name for the facet.
|
EMAIL_DOMAINS
A human readable name for the facet.
|
EMPLOYEE_COUNT_RANGE
A human readable name for the facet.
|
END_YEAR
A human readable name for the facet.
|
FOUNDED_YEAR
A human readable name for the facet.
|
ID
A human readable name for the facet.
|
INDUSTRY
A human readable name for the facet.
|
LOCATIONS
A human readable name for the facet.
|
LOCATIONS_ADDRESS
A human readable name for the facet.
|
LOCATIONS_ADDRESS_CITY
A human readable name for the facet.
|
LOCATIONS_ADDRESS_COUNTRY_CODE
A human readable name for the facet.
|
LOCATIONS_ADDRESS_POSTAL_CODE
A human readable name for the facet.
|
LOCATIONS_ADDRESS_REGION_CODE
A human readable name for the facet.
|
LOCATIONS_ADDRESS_STATE
A human readable name for the facet.
|
LOCATIONS_ADDRESS_STREET1
A human readable name for the facet.
|
LOCATIONS_ADDRESS_STREET2
A human readable name for the facet.
|
LOCATIONS_CONTACT_INFO
A human readable name for the facet.
|
LOCATIONS_CONTACT_INFO_FAX
A human readable name for the facet.
|
LOCATIONS_CONTACT_INFO_PHONE1
A human readable name for the facet.
|
LOCATIONS_CONTACT_INFO_PHONE2
A human readable name for the facet.
|
LOCATIONS_DESCRIPTION
A human readable name for the facet.
|
LOCATIONS_IS_ACTIVE
A human readable name for the facet.
|
LOCATIONS_IS_HEADQUARTERS
A human readable name for the facet.
|
LOGO_URL
A human readable name for the facet.
|
NAME
A human readable name for the facet.
|
NUM_FOLLOWERS
A human readable name for the facet.
|
SPECIALTIES
A human readable name for the facet.
|
SQUARE_LOGO_URL
A human readable name for the facet.
|
STATUS
A human readable name for the facet.
|
STOCK_EXCHANGE
A human readable name for the facet.
|
TICKER
A human readable name for the facet.
|
TWITTER_ID
A human readable name for the facet.
|
UNIVERSAL_NAME
A human readable name for the facet.
|
WEBSITE_URL
A human readable name for the facet.
|
| Modifier and Type | Method and Description |
|---|---|
java.lang.String |
fieldName() |
static CompanyField |
fromString(java.lang.String symbol) |
CompanyField |
parent()
Parent.
|
java.lang.String |
toString()
Method description
|
static CompanyField |
valueOf(java.lang.String name)
Returns the enum constant of this type with the specified name.
|
static CompanyField[] |
values()
Returns an array containing the constants of this enum type, in
the order they are declared.
|
public static final CompanyField ID
public static final CompanyField NAME
public static final CompanyField UNIVERSAL_NAME
public static final CompanyField EMAIL_DOMAINS
public static final CompanyField COMPANY_TYPE
public static final CompanyField TICKER
public static final CompanyField WEBSITE_URL
public static final CompanyField INDUSTRY
public static final CompanyField STATUS
public static final CompanyField LOGO_URL
public static final CompanyField SQUARE_LOGO_URL
public static final CompanyField BLOG_RSS_URL
public static final CompanyField TWITTER_ID
public static final CompanyField EMPLOYEE_COUNT_RANGE
public static final CompanyField SPECIALTIES
public static final CompanyField LOCATIONS
public static final CompanyField LOCATIONS_DESCRIPTION
public static final CompanyField LOCATIONS_IS_HEADQUARTERS
public static final CompanyField LOCATIONS_IS_ACTIVE
public static final CompanyField LOCATIONS_ADDRESS
public static final CompanyField LOCATIONS_ADDRESS_STREET1
public static final CompanyField LOCATIONS_ADDRESS_STREET2
public static final CompanyField LOCATIONS_ADDRESS_CITY
public static final CompanyField LOCATIONS_ADDRESS_STATE
public static final CompanyField LOCATIONS_ADDRESS_POSTAL_CODE
public static final CompanyField LOCATIONS_ADDRESS_COUNTRY_CODE
public static final CompanyField LOCATIONS_ADDRESS_REGION_CODE
public static final CompanyField LOCATIONS_CONTACT_INFO
public static final CompanyField LOCATIONS_CONTACT_INFO_PHONE1
public static final CompanyField LOCATIONS_CONTACT_INFO_PHONE2
public static final CompanyField LOCATIONS_CONTACT_INFO_FAX
public static final CompanyField DESCRIPTION
public static final CompanyField STOCK_EXCHANGE
public static final CompanyField FOUNDED_YEAR
public static final CompanyField END_YEAR
public static final CompanyField NUM_FOLLOWERS
public static CompanyField[] values()
for (CompanyField c : CompanyField.values()) System.out.println(c);
public static CompanyField valueOf(java.lang.String name)
name
- the name of the enum constant to be returned.java.lang.IllegalArgumentException
- if this enum type has no constant
with the specified namejava.lang.NullPointerException
- if the argument is nullpublic java.lang.String fieldName()
public java.lang.String toString()
toString
in class java.lang.Enum<CompanyField>
public static CompanyField fromString(java.lang.String symbol)
public CompanyField parent()
CompositeEnum
parent
in interface CompositeEnum<CompanyField>


Mark Twain once wrote, “I didn’t have time to write a short letter, so I wrote a long one.”
A lightning talk is the modern day equivalent of Twain’s letter. Each presentation is only five minutes long. The challenge lies in delivering something of value within that short timeframe. Lightning talks are a cornerstone of the software industry - especially within the Ruby community - and regularly occur during conferences and meetups. The goal of Hungry Academy is not just to teach us coding but also to bring us into the wider development world - which makes preparing and giving lightning talks an important part of the Hungry Academy curriculum. Every Friday morning, 8-12 of us deliver a talk on the topic of the week. Topics so far have ranged from the Ruby community at large to authentication and testing tools.
Why Important
Lightning talks are great for two reasons.  Because of the nature of our work, we often do not have many opportunities to practice “soft” business skills. In the past this has led to developers taking the role of code monkeys that simply need to be fed tasks. Ironically, developers are in fact excellent problem solvers, and given the opportunity they can contribute greatly to the direction of their companies. Lightning talks help bridge the communications gap, turning mere coders into business leaders.
Meanwhile, giving a presentation in under five minutes reqires a clear, concise understanding of the topic. Your mastery will continue develop as you educate others. Lightning talks are a good skill to foster, increasing both soft business skills and technical mastery.
Tips on Preparing
Because lightning talks are shorter, preparing for them is different than for a standard presentation.
Here are five tips for success:
1) Center your talk around one point and make that point as early as possible. Although you usually have 5 minutes for the lightning talk, if the point can be made in two - take two. 2) Keep background information to a minimum. The audience for most lightening talks is made up of smart, problem solving individuals. They don’t need their hands held. Just make your point. 3) Slides are not required. Think of a lightning talk as a conversation you have with a group of your friends, but they keep quiet for five minutes. A fancy chart isn’t necessary to make your point. 4) DO NOT LIVE CODE. EVER. DON’T DO IT. DON’T EVEN TRY. Murphy’s law will bite you. Use a screencast or screenshot instead. 5) Practice. Your presentation is five minutes but without practice it is just a waste of your audience’s time. Remember who is watching - people who live and breathe efficiency.
Check back on the Hungry Academy site in the next few days and weeks as we begin publishing screencasts and videos from our weekly lightning talks!


Ghent, Belgium | 6 & 7 December 2018
Attend a workshop and pick up tips and tricks from Angular experts.
Socialize with Angular experts, attend talks and connect with the Angular Core team.


Tags defined in Moya Auth library.
| Tag | Synopsis |
|---|---|
| <add-permission> | add a permission to a group or user |
| <add-user-to-group> | add a user to a group |
| <check-password> | check a user password |
| <get-permissions> | query user permissions |
| <get-user> | get current user details |
| <login> | log in a user with username/password |
| <login-user> | log in a user |
| <logout> | log out a user |
| <new-permission> | create a new permission |
| <new-user> | create a new user |
| <set-password> | set a user's password |


The page's maximum width is 1280px
When the page is viewed on a small screen, the aside part is displayed below the main part
Colors used are:


Authors: Guy Vandenbosch
Source:FERMAT, Volume 22, Communication 12, Jul.-Aug., 2017
Abstract: This presentation overviews the antenna activities at the KU Leuven, Leuven, Belgium. Each of the five general strategic research lines (EM theory, computational EM, antenna analysis and design, antenna fabrication, and antenna measurements) is described and substantiated by giving representative examples of the performed research and the obtained results. The largest activity is the design of innovating antenna radiators and systems for a multitude of different applications, for example beam steered antennas, wearable antennas, mm wave antennas, and antennas inspired by practical problems in industry. The most recent is the research activity on nano-antennas, which is performed in close operation with several physics departments worldwide.
Index Terms: research strategy, research lines, antenna design
View PDF
Radiation and antenna group @ Katholieke Universiteit Leuven


Block superficial pull requests
Code review is a tedious task as it is so why make it harder? Superficial changes are files that only have style changes without any update to functionality.


Testing Strategy
For each component of our solution, we used different testing approaches. For instance, we used mainly manual testing for the data pipeline, whereas for the data visualization we used automated unit tests. In addition, we conducted usability tests on users from various backgrounds.
Data Pipeline
The ML SVM prediction model was manually tested by visualising the results produced. In addition, its performance was compared to the Linear Regression model by comparing the mean absolute error and the R2 score.
Progressive Web App
To ensure that the progressive web app behaves as expected, we first started writing unit tests. For the JavaScript code, we used the Jest universal testing platform. All the test files were written in the test folder of our PWA, and they can be executed using the "npm test" command.
To ensure that the progressive web app behaves as expected, we first started writing unit tests. For the JavaScript code, we used the Jest universal testing platform. All the test files were written in the test folder of our PWA, and they can be executed using the "npm test" command. Additionally, our build pipeline implemented in the Azure DevOps project will run the test and report any failure before producing the build artifact.
For the Azure Maps visualization, the code was written following the "separation of concern" design pattern. Thus, testing the application logic did not require mocking the functionalities provided by our API nor by the Azure Maps JavaScript library. For instance, we test that only the unique FAD ids are added to the map by providing a mock JSON object instead of the full dataset. By mocking the data for a FAD, we check the validity of the HTML created for its additional details. Similarly, we check the options for map objects such as lines.
In order to test the searching elements section of our PWA (at the bottom of the UI which you can select particular elements to search), we firstly ensure that the list for indicating the selected searching elements can be changed correctly. We use a list to pass required searching elements to the searching result page. Everytime the user selects an element, the corresponding keyword will be pushed to the list (A second click will remove it of course), then the data views page knows that it should display those particular data. By trying to push different elements to the list respectively and check the returned list, we can ensure that the list performs correctly. Secondly, we need to make sure that the information passed to the data views pages are correct. We use the URL ( html file name + ? + the list ) to tell the data views page which part of data should be displayed. By trying to assign different lists to the URL, and check the returned URL string, we can know whether the data views page can get the correct instructions. Then it comes to the API’s part.
API
To test the API, we used the request Python Library, which allows sending HTTP requests. For instance, by sending GET requests to the API, we tested that either the correct data was retrieved for a particular FAD id, or the 404 status code was sent if no data was found. Similarly, by sending PUT requests, we tested that the new FAD data is indeed added to the dataset.
User Acceptance Testing
We went through the codes and functionalities with our project partners during the last few weeks. Generally, we tested the core functionalities, with related code explained to them. We followed the overall pipeline of our project (Upload -> Store -> View) to see the perfomance of the product. Our project partners said that most parts are good, and they gave us some suggestions.
Firstly, the Azure account information (such as Access Keys) should be provided by the users when they deploying our project. We should not contain any information of our own Azure accounts, which is inappropriate and unsafe.
Secondly, instead of using the “magical number” (We originally used a list with four int, initialised to [0, 0, 0, 0] to pass searching elements. If a particular element is selected, we change the integer with corresponding index to 1.), we could use keywords in the list to tell the result page about the searching elements selected. We can initialise an empty list, when an element is selected, we can just push that keyword to the list. The benefit of doing this is that this approach is not only friendly for the developer since it clearly shows the information, but also for the actual users because they can understand the searching elements by their URL. Furthermore, they can even directly type in the elements they want to search follow the URL without operating them on the home page.
We also met our potential clients from Invictus FAD Team from Saint Lucia. We did a presentation to them, to demonstrate our implemented functionalities. They said that this is exactly what they want, and they appreciated for our hard works.


Build fullstack and API applications with PostgreSQL databases. Fluent in Rspec and Minitest testing libraries.
Build applications using Javascript(ES6) on client and server side. Framework of choice is React.
Build native mobile applications with React Native.
In January 2017, I packed up my bags and moved to Denver, Colorado to attend The Turing School of Software & Design's Backend Engineering Program. Lasting a duration of 7 months, the program moves from the basics of object-oriented programming and data structures to building database-backed web applications using Javascript and Ruby on Rails.
Shortly after moving back to New York, I started working with Andrew Glass to help assist with various ongoing projects. The consultancy builds web applications for local clients spanning multiple industries.
At the tail end of 2017, I teamed up with the Covet crew to help build upon their mobile and web platforms. Covet's mission is to bring concierge services to the suburbs. Growing up in Long Island, I connected with their vision and strive to bring their product to suburban houses.
During the summer of 2018, I joined Karlie Kloss and the Kode With Klossy team to help teach girls aged 15-19 fundamental coding skills. As an instructor, I educated students on Ruby, HTML, CSS, APIs and Sinatra.
In the fall of 2018, I joined AdhereTech as a fullstack developer. AdhereTech provides highly-effective adherence programs, via smart wireless pill bottles.


In the JMockit toolkit, the Expectations & Verifications
APIs provide rich support for the creation of
behavior-based unit tests.
The focus when doing this kind of testing is on the interactions between the unit under test and the other
units it depends upon. Such units of behavior are the classes, methods, and constructors defined in production code.
An interaction between two units always takes the form of a method or constructor invocation. The set of invocations from a unit under test to its dependencies, together with the argument and return values passed between them, define the behavior of interest for the tests of that particular unit. In addition, a given test may need to verify the relative order of execution between multiple invocations.
The methods and constructors which are invoked from the unit under test, and which belong to a dependency of that
unit, will be our regular targets for mocking.
We tell JMockit what needs to be mocked by specifying mocked types.
A mocked type should be the type of a dependency of the unit under test.
Such a type can be any reference type: an interface, an abstract class, a concrete class, a final
class,
and so on (more on this later).
By default, all methods and constructors (in case of a class) of the mocked type will be mocked.
If the declared mocked type is a class, then all of its super-classes up to but not including
java.lang.Object
will also be mocked, recursively.
Therefore, inherited methods will automatically be mocked as well.
When a method or constructor is mocked, its original implementation code won't be executed on invocations from the test. Instead, the call will be redirected to JMockit so it can be dealt with in the manner that was explicitly or implicitly specified in the test method, as we will see in the remaining of this chapter.
The following example test serves as a basic illustration for the declaration of mocked types. In this tutorial, we use many code snippets like this, where the parts in bold font are the current focus of explanation.
@Test
public void doBusinessOperationXyz()
{
...
new Expectations()
{
Dependency mockInstance; // "Dependency" is our mocked type for this test
...
{
...
mockInstance.mockedMethod(...);
...
}
};
...
}
An expectation is a set of invocations to an specific mocked method/constructor that is relevant for a given test. An expectation may encompass multiple different invocations to the same method or constructor, but it does not have to encompass all such invocations that occur during the test execution.
Besides being associated with an specific method or constructor, each expectation will specify argument values for
the corresponding method/constructor invocations, when there are one or more invocation parameters involved.
For each parameter, an exact argument value may be specified, according to the parameter type.
For example, the value "test string"
for an String
parameter.
As we will see later, instead of specifying exact argument values, we can specify constraints on such values, which
will match whole sets of different argument values, for one or more actual invocations.
The example below shows an expectation for someMethod(int, String)
, which will match an invocation to
this method that should receive the exact argument values as specified.
Notice that the expectation itself is specified through an invocation to the mocked method.
This invocation, however, does not count as one of the "real" invocations we are interested in testing.
It's only there so that the expectation can be specified.
@Test
public void doBusinessOperationXyz()
{
...
new Expectations()
{
Dependency mockInstance;
...
{
...
// An expectation for an instance method:
mockInstance.someMethod(1, "test");
...
}
};
// A call to the unit under test occurs here, leading to the mock
// invocations associated with one or more expectations.
}
We will see more about expectations later, after we understand the differences between recording and verifying individual invocations.
Any developer test can be divided in at least three separate execution phases. The phases execute sequentially, one at a time, as demonstrated below.
@Test
public void someTestMethod()
{
// 1. Preparation: whatever is required before the unit under test can be exercised.
...
// 2. The unit under test is exercised, normally by calling a non-private method
// or constructor.
...
// 3. Verification: whatever needs to be checked to make sure the exercised unit
// did its job.
...
}
First, we have a preparation phase, where objects and data items needed for the test are created or obtained from somewhere else. Then, the unit under test is exercised. Finally, the results from exercising the tested unit are compared with the expected results.
This model of three phases is also known as the Arrange, Act, Assert syntax, or "AAA" for short. Different words, but the meaning is exactly the same.
In the context of behavior-based testing with mocks, we can identify the following alternative phases, which are directly related to the three previously described conventional testing phases.
Behavior-based tests written with JMockit will typically look like the following:
import mockit.*;
... other imports ...
public class SomeTest
{
// Zero or more "mock fields" common to all test methods in the class:
@Mocked Collaborator mockCollaborator;
@NonStrict AnotherDependency anotherDependency;
...
@Test
public void test1(mock parameters)
{
// Preparation code not specific to JMockit, if any.
new Expectations() // an "expectation block"
{
// Zero or more mock fields.
{
// One or more invocations to mocked types, causing expectations to be recorded.
// Invocations to non-mocked types are also allowed anywhere inside this block.
}
};
// Unit under test is exercised.
// Verification code, if any.
}
@Test
public void test2(mock parameters)
{
// Preparation code not specific to JMockit, if any.
// Unit under test is exercised.
new Verifications() // a "verification block"
{
{
// One or more invocations to mocked types, causing expectations to be verified.
}
};
// Additional verification code, if any, either here or before the verification block.
}
@Test
public void test3(mock parameters)
{
// Preparation code not specific to JMockit, if any.
new NonStrictExpectations() // also an expectation block
{
// Zero or more mock fields.
{
// One or more invocations to mocked types, causing expectations to be recorded.
// Invocations to non-mocked types are also allowed anywhere inside this block.
}
};
// Unit under test is exercised.
new VerificationsInOrder() // also a verifications block
{
{
// One or more invocations to mocked types, causing expectations to be verified.
}
};
// Additional verification code, if any, either here or before the verification block.
}
}
There are other variations to the above templates, but the essence is that the expectation blocks belong to the record phase and come before the unit under test is exercised, while the verification blocks belong to the verify phase. A test method can contain any number of expectation blocks, including none. The same is true for verification blocks.
The fact that anonymous inner classes are used to demarcate blocks of code allows us to take advantage of the "code folding" feature available in modern Java IDEs. The following image shows what it looks like in IntelliJ IDEA.
A mocked type can be introduced either through an instance field or a parameter declaration.
In the first case, the field belongs to the test class or to a mockit.Expectations
subclass (a local field inside an expectation block).
In the second case, the parameter belongs to a test method.
In all cases, a mock field/parameter declaration can use the mockit.Mocked
annotation.
The use of this annotation is optional for mock parameters and for mock fields declared inside expectation blocks.
It's only required for mock fields declared in the test class, in order to avoid confusion with other fields the test
class might have that are not intended for mocking.
All kinds of Java types are valid for mock fields and parameters, except for primitive types and for array types.
So, to make it clear, the following reference types are valid: interfaces, concrete classes, abstract
classes, final
classes, enum
types, and annotation types.
Note that this includes reference types from the JRE (belonging to one of the standard packages, like
java.lang
, java.util
, and so on).
For a mock parameter, an instance of the declared type will be automatically created by JMockit and passed in the
call to the test method. It will never be null
.
For a mock field, an instance of the declared type will be automatically created by JMockit and assigned to the
field, unless it's a final
field.
In this case, a value should be assigned to the field explicitly in test code. Such a value can be null
,
though, which is perfectly valid for a mocked class if only constructors and static methods are going to be called on
it.
The mocked instances created by JMockit can be used normally in test code, and/or passed to the code under test.
Differently from other mocking APIs, though, these mocked objects don't have to be the ones used by the unit
under test when it calls instance methods on its dependencies.
By default, JMockit does not care on which object a mocked instance method is called.
This is what allows the transparent mocking of instances created directly inside code under test through invocations
to constructors using the new
operator.
The classes instantiated must be covered by mocked types declared in test code, that's all.
Finally, note that the mocked instances created by JMockit are similar to the traditional mock objects created by other mocking tools, but they are not the same. With the JMockit Expectations API, every instance of a mocked type - whether created by JMockit or not - is mocked, for as long as that type remains mocked. With a more traditional mocking API, only the mock objects/instances created by the mocking tool are actually mocked. Most of the time, this makes little or no difference when writing tests, but it is something to keep in mind.
Suppose the unit under test needs to be given an object which implements two or more interfaces. Can we get a mocked instance which satisfies this requirement? One way to do it would be to create a test-specific interface which extends all the interfaces required by the tested unit, and then use that as the mocked type. There is a better way though, which does not require the definition of a new interface, as the following example tests show.
interface Dependency // an arbitrary custom interface
{
String doSomething(boolean b);
}
public final class MultiMocksTest<MultiMock extends Dependency & Runnable>
{
@Mocked MultiMock multiMock;
@Test
public void mockFieldWithTwoInterfaces()
{
new NonStrictExpectations()
{
{
multiMock.doSomething(false); returns("test");
}
};
multiMock.run();
assertEquals("test", multiMock.doSomething(false));
new Verifications()
{
{
multiMock.run();
}
};
}
@Test
public <M extends Dependency & Serializable> void mockParameterWithTwoInterfaces(final M mock)
{
new Expectations()
{
{
mock.doSomething(true); returns("");
}
};
assertEquals("", mock.doSomething(true));
}
}
In each of the tests above, two interfaces were mocked together: Dependency
plus
java.lang.Runnable
for a mock field, and Dependency
plus
java.io.Serializable
for a mock parameter.
We used the type variables MultiMock
(defined for the whole test class) and
M
(defined for a single test method) so that JMockit could know about the component
interfaces in each case.
For a given method with non-void
return type, a return value can be recorded through the
Expectations#result
field or through the Expectations#returns(...)
method.
When the method gets called in the replay phase, the specified return value will be returned to the caller (which
normally is the unit under test).
If the test instead needs an exception or error to be thrown when the method is invoked, then the result
field can also be used to record the desired exception/error to be thrown, by having the desired throwable instance
assigned to it.
In the rare case where a method actually returns exception or error objects, the returns(Object)
method
will have to be used, to avoid the ambiguity.
Note that recording exceptions/errors to be thrown is applicable to mocked methods as well as to mocked constructors.
Multiple consecutive results (values to return and/or throwables to throw) can be recorded for the same expectation,
by simply assigning the result
field multiple times after the mock invocation that creates the
expectation.
The recording of multiple return values and/or exceptions/errors to be thrown can be freely mixed for the same
expectation.
In the case of recording multiple consecutive return values for a given expectation, a single call to the
returns(Object, Object...)
method can be made to specify more than one return value.
The result
field can also be used, by assigning it a list or array of the consecutive values.
For more details about this ability, see the corresponding
API documentation.
The following example test records expectations for two methods defined in a mocked class.
The first one specifies that the unit under test should first invoke intReturningMethod()
on an instance
(any instance) of the mocked class, which will then return the value 5
.
The second one specifies that the unit under test should then invoke stringReturningMethod()
three
times, with the first two calls resulting in the return values of "str1"
and "str2"
, and
the third call causing an IllegalStateException
instance to be thrown.
@Test
public void someTestMethod()
{
new Expectations()
{
final DependencyAbc abc = new DependencyAbc();
{
abc.intReturningMethod(); result = 5;
abc.stringReturningMethod(); returns("str1", "str2");
result = new IllegalStateException();
}
};
new UnitUnderTest().doSomething();
}
The example above actually contains three different expectations.
The call to the DependencyAbc()
constructor in the mock field assignment turns out to also be a mock
invocation inside the expectation block, and as such it also defines an expectation.
In fact, there was no need to call the constructor in the field assignment.
Moving new DependencyAbc();
to the beginning of the instance initialization block and leaving the mock
field unassigned would have worked just as well.
Often, however, it's not desirable or important to specify all these method and constructor invocations in a given
test. We will soon address this issue.
Whenever an invocation to a mocked non-void
method fails to match any recorded expectation, a default
return value needs to be provided.
JMockit will always supply a reasonable return value, according to the declared return type of the method:
0
(zero) for an integral primitive type, false
for boolean
, an empty
collection or array, or the null
reference for reference types (including String
and the
primitive wrapper classes).
Mocked constructors and void
methods also have a "default result", which is to simply return without
throwing any exception or error.
(Note, however, that when an invocation is deemed to be unexpected, an AssertionError
is
thrown instead of returning a value.)
It's possible to explicitly override such default results in an expectation block, by declaring input
fields. Such (instance) fields must be annotated with @Input
. Here is an example.
@Test
public void someTestMethod()
{
new NonStrictExpectations()
{
DependencyAbc mock; // a mock field, assigned automatically
// The names of input fields are merely for documentation.
@Input final int defaultIntReturn = 5;
@Input Socket aSocket;
@Input FileNotFoundException onFileOpen;
{
abc.stringReturningMethod(); returns("str1", "str2");
}
};
new UnitUnderTest().doSomething();
}
In the case of return values, the declared type of the field must be the same as the return type of interest; any
non-void
methods having this return type will return the value assigned to the input field,
each time they get invoked by the code under test, provided they are allowed to occur and there is no
matching recorded expectation.
In the example above, any method belonging to DependencyAbc
which returns an int
will
return the value 5
; any method returning a Socket
will return a socket object instantiated
automatically with the java.net.Socket
public no-args constructor (if a custom instance was needed, we
could have it explicitly instantiated and assigned to the field).
Methods or constructors that declare to throw checked exceptions can have one such exception specified as
the default result, by simply declaring an input field of the desired exception type. An exception instance can be
directly instantiated and assigned to the field; if none is, then JMockit will do so automatically using the public
no-args constructor of the exception class.
In the example test, if DependencyAbc
has a method or constructor with
java.io.FileNotFoundException
in its throws
clause, it will cause this exception to be
thrown whenever a non-recorded invocation occurs during the test.
Note that this mechanism depends only on return types or throws clauses, not on method names or
parameters, or even on which mocked class or instance an invocation occurs.
For many methods in production code, we often find that only one value of a certain type is needed for a
given test of the method (particularly when it's a reference type, less so when it's a primitive or
String
).
This property allows us to write a shorter test, where a "mere" default result is specified instead of having to
record an expectation and deal with full method/constructor signatures.
When more precision is required for a given test, a suitable expectation will have to be recorded, naturally.
On the previous section we mentioned that a recorded invocation like abc.intReturningMethod();
would
actually match invocations to DependencyAbc#intReturningMethod()
on any instance of the mocked
DependencyAbc
class.
In most cases, this won't really matter and can be safely ignored.
But what if we need to verify that the invocation occurs on a specific instance?
We use the Expectations#onInstance(mockObject)
method when recording the invocation,
as the next example shows.
@Test
public void matchOnMockInstance(final Collaborator mock)
{
new Expectations()
{
{
onInstance(mock).getValue(); result = 12;
}
};
// Exercise unit under test with the mocked instance passed from the test:
int result = mock.getValue();
assertEquals(12, result);
}
The test above will only pass if the unit under test invokes getValue()
on the exact
same mock instance on which the recording invocation was made.
This is typically useful when the unit under test makes calls on two or more different instances
of the same type, and the test wants to verify that each invocation occurred on the proper instance.
In fact, whenever two or more mocks of the exact same type are in scope for a given test, JMockit
will automatically apply "onInstance" matching to all invocations made on those mocks.
Therefore, in such common situations it isn't necessary to explicitly use the onInstance(mock)
method.
In practice, this matching specifier method will rarely be used.
For a real-world example of this functionality, see the CompositeEffectTest#testInit
test from the Timing Framework sample test suite.
In both the record and verify phases, an invocation to a mocked method or
constructor identifies an expectation.
If the method/constructor has one or more parameters, then a recorded/verified invocation like
doSomething(1, "s", true);
will only match an invocation in the replay
phase if it has identical argument values.
In a given test, we often don't know exactly what those argument values will be, or they simply
aren't essential for what is being tested.
So, to allow a recorded or verified invocation to match a whole set of replayed invocations with
different argument values, we can specify flexible argument matching constraints instead
of equal argument values.
This is done through a set of withXyz(...)
methods of the
mockit.Invocations
base class (which both mockit.Expectations
and
mockit.Verifications
extend), where "Xyz" describes the specific matching constraint.
See examples below.
@Test
public void someTestMethod(@NonStrict final DependencyAbc abc)
{
final DataItem item = new DataItem(...);
new Expectations()
{
{
// Will match "new DependencyAbc(int)" invocations with any int-valued argument.
new DependencyAbc(withAny(0));
// Will match "voidMethod(String, List)" invocations with the first argument
// equal to "str" and the second not null.
abc.voidMethod("str", (List<?>) withNotNull());
// Will match invocations to DependencyAbc#stringReturningMethod(DataItem, String)
// with the first argument pointing to "item" and the second one containing "xyz".
abc.stringReturningMethod(withSameInstance(item), withSubstring("xyz"));
}
};
new UnitUnderTest().doSomething(item);
new Verifications()
{
{
// Matches invocations to the specified method with any long-valued argument.
abc.anotherVoidMethod((long) withAny());
}
};
}
There are more "with" methods than shown above. See the API documentation for more details.
Besides the several predefined argument matching constraints available in the API, JMockit allows the user to provide
custom constraints, through the <T> T with(Object)
and <T> T with(T, Object>)
generic
methods.
The parameter of type Object
can be an org.hamcrest.Matcher
object from the Hamcrest library, or a suitable handler object
(see the API documentation for details).
For the withAny(?)
methods that take no arguments or take one only to designate
the parameter type, there is a set of special argument matching fields that are
available to expectation and verification blocks.
Using these "any" fields will have the same effect as using the corresponding "withAny" method, as demonstrated
below.
@Test
public void someTestMethod(@NonStrict final DependencyAbc abc)
{
final DataItem item = new DataItem(...);
new Expectations()
{
{
// Will match "new DependencyAbc(int)" invocations with any int-valued argument.
new DependencyAbc(anyInt);
// Will match "voidMethod(String, List)" invocations where the first argument is
// "str" but the second can be anything.
abc.voidMethod("str", (List<?>) any);
}
};
new UnitUnderTest().doSomething(item);
new Verifications()
{
{
// Matches invocations to the specified method with any long-valued argument.
abc.anotherVoidMethod(anyLong);
}
};
}
Again, see the API documentation for more details on argument matching fields.
null
value to match any object reference
When using at least one argument matching method or field for a given expectation, we can specify
that any object reference be accepted for a parameter of reference type by simply passing the
null
value instead of a withAny()
or any
argument matcher.
In particular, this avoids the need to cast the value to the declared parameter type.
However, bear in mind that this behavior is only applicable when at least one explicit
argument matcher (either a "with" method or an "any" field) is used for the expectation.
When passed in an invocation that uses no matchers, the null
value will match only
the null
reference.
In the previous test, we could therefore have written:
@Test
public void someTestMethod(@NonStrict final DependencyAbc abc)
{
...
new Expectations()
{
{
...
abc.voidMethod(withEqual("str"), null);
}
};
...
}
When one or more explicit matchers are present and the null
reference must be
matched for a given parameter, the withNull()
method should be used.
In conclusion, there are two modes for argument matching: the basic one where no
matching constraints are specified and all arguments must be equal, and the one where matching
constraints are specified for some or all parameters.
The meaning of the null
value is different for each mode, which may lead to confusion at times.
For complex invocations where multiple arguments are involved, though, the benefits of being able
to use "any" fields and the null
reference should outweigh the additional API complexity.
to be written
So far, we saw that besides an associated method or constructor, an expectation can have a list of invocation results (a mix of return values for non-void methods, and/or thrown exceptions/errors) and also an argument matcher for each method/constructor parameter. Given that the unit under test can call the same method or constructor multiple times, with different or identical arguments, we need a way to account for all those separate invocations. One way, as already seen, is to simply record one separate invocation for each expected invocation; another is to record two or more expected results (each either a return value or a thrown exception/error) following a single mock invocation.
Yet another way, particularly useful for void
methods or when the test doesn't care
about specific return values, is to specify an invocation count constraint for a given expectation.
The API has several fields just for that: times
, minTimes
, and maxTimes
.
These fields belong to the mockit.Invocations
class, the non-public base class for
both mockit.Expectations
and mockit.Verifications
.
Therefore, an invocation count constraint can be specified either when recording or when verifying invocations.
In either case, the method or constructor associated with the expectation will be constrained to
have a number of invocations made by the unit under test that falls in the specified range.
Any invocations less or more than the expected lower or upper limit, respectively, and the test
execution will automatically fail.
@Test
public void someTestMethod(final DependencyAbc abc)
{
new Expectations()
{
{
// By default, one invocation is expected, ie "times = 1;":
new DependencyAbc();
// At least two invocations are expected:
abc.voidMethod(); minTimes = 2;
// 1 to 5 invocations are expected:
abc.stringReturningMethod(); minTimes = 1; maxTimes = 5;
}
};
new UnitUnderTest().doSomething();
}
@Test
public void someOtherTestMethod(final DependencyAbc abc)
{
new UnitUnderTest().doSomething();
new Verifications()
{
{
// Verifies that zero or one invocations occurred, with the specified argument value:
abc.anotherVoidMethod(3); maxTimes = 1;
// Verifies the occurrence of at least one invocation with the specified arguments:
DependencyAbc.someStaticMethod("test", false); // "minTimes = 1" is implied
}
};
}
Expectations recorded inside a new Expectations() {...}
block are all
strict by default, meaning that the invocations they specify are expected to
occur during the replay phase, and in the same order as they were recorded.
Even more, only these explicitly recorded expected invocations will be allowed to occur.
Any unexpected invocations that were not recorded will automatically cause the test to fail.
The mockit.NonStrictExpectations
class (which extends
mockit.Expectations
), as the name indicates, is used when we want to record
non-strict (or loose) expectations.
Inside such a block, all invocations to mocked types will be allowed to occur during the
replay phase, not expected. That is, by default they may or may not occur during replay.
In addition, they don't have to occur in the same order as they were recorded.
By default, an invocation recorded as an strict expectation will be expected to match exactly one
invocation in the replay phase. That is, the expectation will have an invocation count constraint
of 1
, as if it was followed by times = 1
assignment.
An invocation recorded as non-strict, on the other hand, will by default be allowed to match any
number of invocations in the replay phase. That is, its invocation count constraint will have a
lower limit of 0
and an unbounded upper limit, as if followed by a minTimes = 0
assignment.
In either case, however, the default invocation count constraint can be overridden by an explicit
one (that is, an explicit assignment to one of the times/minTimes/maxTimes
fields).
Notice that in the case of strict expectations, all the invocations occurring in the replay phase
which match a recorded strict expectation are implicitly verified.
The remaining invocations will be considered unexpected (and fail the test), unless the
associated mocked type is not strict.
So, the use of strict expectations which are verified implicitly precludes the use of
verification blocks, which are used for explicit verification of invocations.
In fact, inside a new Verifications() {...}
block only invocations matching
recorded non-strict expectations are permitted, as well as invocations to non-strict mocked types
for which no expectation was explicitly recorded.
To allow mixing strict and non-strict expectations inside an strict expectation block, we can
apply the mockit.NonStrict
annotation to a mock field or parameter.
Any invocation to such a mocked type will be considered as belonging to a non-strict expectation,
and all unrecorded invocations in the replay phase will be allowed (that is, they will never be
considered as unexpected, and therefore will not cause the test to fail).
This is particularly useful to avoid the need to record invocations to constructors, or to any
uninteresting methods.
Inside an strict expectation block, an individual invocation can be explicitly marked as
non-strict through a notStrict()
call following the invocation.
Most of the time, it will be easier to use a non-strict expectation block or a mock
field/parameter annotated as non-strict, though.
So, how do we choose between strict and non-strict expectations for a given test? There is really no general-purpose answer to this question. It will depend on the particulars of the unit under test, and on personal preferences. Also, keep in mind that a test can mix both kinds of expectations, so there is a lot of flexibility in using them.
It's usually best to think about strictness at the level of individual expectations, not at the level of mocked instances or types. That said, it is also correct to say that a given mocked instance (or mocked type) is strict or non-strict. All it means, really, is that all expectations associated to that particular instance/type have the same strictness. On the other hand, it's perfectly valid to record both strict and non-strict expectations for the same mocked instance or type, in the same test. And when using mock fields declared at the test class level, it's possible that a given mocked instance will be entirely strict in one test and entirely non-strict in another, in the same test class.
The JMockit Expectations API lets you specify that a given recorded expectation should be
non-strict (through the notStrict()
method), that all expectations for a particular
mock should be non-strict (by annotating the mock field or parameter with
@NonStrict
), and that all expectations recorded inside a particular block should be
non-strict (by extending the NonStrictExpectations
base class).
That's it. There is no way to specify that a given expectation, a mock, or a whole expectation block should be
strict.
Strict expectations are recorded and verified by default, when we do not
specify that they should be non-strict. For an expectation to be strict, it needs to be recorded
inside an expectation block not derived from NonStrictExpectations
, for a mocked
type not annotated as @NonStrict
.
Remember that unexpected invocations can only be detected for so-called strict mocks, or for
expectations with an specified maximum invocation count constraint.
So, how do we obtain a mocked instance/type where all unrecorded expectations are considered to
be strict (and therefore cause matching invocations at replay time to throw an "unexpected
invocation" error)? Simple: by recording at least one strict expectation on the mocked
instance/type. Note that this rules out the use of empty expectation blocks.
If you need to specify that no invocations are allowed on a given mock, then either record a
strict expectation with a times = 0
constraint or use a
FullVerifications
block (explained in the next section).
When a sequence of consecutive invocations is recorded with strict expectations (the relative
order between invocations is irrelevant with non-strict expectations), the whole
sequence is expected to occur exactly once during the replay phase.
Consider, however, the case where the tested code executes those invocations in a loop (or any kind of iteration).
Assuming that the number of iterations is known in the test, we can still record those
expectations with a single invocation to each method/constructor called inside the loop (that is,
without writing a loop or repeating the expectations inside the expectation block).
The next test demonstrates this feature, using the Expectations(int numberOfIterations)
constructor.
@Test
public void recordStrictInvocationsInIteratingBlock(final Collaborator mock)
{
new Expectations(2)
{{
mock.setSomething(anyInt);
mock.save();
}};
// In the tested code:
mock.setSomething(123);
mock.save();
mock.setSomething(45);
mock.save();
}
The ability to specify how many iterations are expected for a group of invocations is typically
used with strict expectations, but it also applies to non-strict expectations.
There is also a NonStrictExpectations(int numberOfIterations)
constructor.
Strict expectations are verified implicitly, so there is no point in re-verifying them in a explicit verification block. Non-strict expectations, on the other hand, are usually verified through explicit invocations to mocked types in a verification block. As will be seen later, a recorded non-strict expectation can still be verified implicitly, without the need to write an invocation inside a verification block.
Inside a new Verifications() {...}
block we can use the same API that's available in
a new NonStrictExpectations() {...}
block, with the exception of the methods and
fields used to record return values and thrown exceptions/errors.
That is, all of the withXyz(...)
argument matching methods can be used, as well as
the times
, minTimes
, and maxTimes
invocation count constraint fields.
Mocked instances and mocked types declared as mock fields of the test class or as mock parameters of the test method are immediately available inside verification blocks. However, expectation blocks can also declare local mock fields, which won't be accessible outside the block. In such cases, it's possible to import those mocked instances into a verification block, as the next example shows.
@Test
public void importLocalMockFromPreviousNonStrictExpectationsBlock()
{
new NonStrictExpectations()
{
Dependency mock;
{
mock.notifyBeforeSave(); result = true;
}
};
// Inside tested code:
Dependency dependency = new Dependency();
dependency.editABunchMoreStuff();
new Verifications()
{
Dependency mock;
{
mock.editABunchMoreStuff();
}
};
}
The mocked types to be imported are identified by the types of the fields declared in the verification, not by the field names. Typically, though, the same field names will be used to avoid confusion. This ability can be useful if for whatever reason mock parameters are not desired, or when capturing internally created instances of mocked types (explained in a later section).
To do this inside a verification block, add a times = 0
assignment right after the
invocation that is expected to not have happened during the replay phase.
If one or more matching invocations did happen, the test will fail.
Regular verification blocks, like the one below, are unordered.
The actual relative order in which aMethod()
and anotherMethod()
were
called during the replay phase is not verified, but only that each method was executed at least once.
@Test
public void someTestMethod(final DependencyAbc abc)
{
...
new Verifications() // order of invocations does not matter
{
{
abc.aMethod();
abc.anotherMethod();
}
};
}
If you do want to also verify the relative order of invocations, then a new VerificationsInOrder() {...}
block must be used instead.
Inside this block, simply write invocations to one or more mocked types in the order they are expected to have
happened.
Naturally, argument matchers and invocation count constraints can be freely used.
Suppose you want to verify that a particular method (or constructor) was called before
(or after) other invocations to mocked types in the replay phase, but you don't care
about the order in which those other invocations occurred.
Inside an ordered verification block (VerificationsInOrder
), this can be achieved by simply calling the
unverifiedInvocations()
method at the appropriate place(s).
The following test snippet demonstrates it.
@Test
public void someTestMethod(final DependencyAbc abc, final AnotherDependency xyz)
{
new UnitUnderTest().doSomething();
new VerificationsInOrder()
{
{
abc.methodThatNeedsToExecuteFirst();
unverifiedInvocations(); // Invocations not verified must come here...
xyz.method1();
abc.method2();
unverifiedInvocations(); // ... and/or here.
xyz.methodThatNeedsToExecuteLast();
}
};
}
The example above is actually quite sophisticated, as it verifies several things: a) a method
that must be called before others; b) a method that must be called after
others; and c) that AnotherDependency#method1()
must be called just before
DependencyAbc#method2()
.
In most tests, we will probably only do one of these different kinds of order-related
verifications. But the power is there to make all kinds of complex verifications quite easily.
Another situation not covered by the examples above is one where we want to verify that certain
invocations occurred in a given relative order, while also verifying the other invocations
(in a given order or in any order).
For this, we need to write two separate verification blocks, as illustrated below (where
mock
is a mock field of the test class).
@Test
public void verifyFirstAndLastCallsWithOthersInBetweenInAnyOrder()
{
exerciseCodeUnderTest();
new VerificationsInOrder()
{{
mock.prepare();
unverifiedInvocations();
mock.notifyBeforeSave();
mock.save();
}};
new Verifications()
{{
mock.setSomething(123);
mock.setSomethingElse("anotherValue");
}};
}
In the test above, the two invocations verified in the second block correspond to the "unverified invocations" from the first block. The relative order of the multiple verification blocks is actually irrelevant; each verification block is evaluated independently from the others.
Sometimes it may be important to have all invocations to the mocked types involved in a test verified.
This is automatically the case when recording strict expectations, since any unexpected invocation causes the test to
fail.
When non-strict expectations are explicitly verified, though, a new FullVerifications() {...}
block can
be used to make sure that no invocations are left unverified.
@Test
public void verifyAllInvocations(final Dependency mock)
{
// Code under test included here for easy reference:
mock.setSomething(123);
mock.setSomethingElse("anotherValue");
mock.setSomething(45);
mock.save();
new FullVerifications()
{{
// Verifications here are unordered, so the following invocations could be in any order.
mock.setSomething(anyInt); // verifies two actual invocations
mock.setSomethingElse(anyString);
mock.save(); // if this verification (or any other above) is removed the test will fail
}};
}
Note that if a lower limit (a minimum invocation count constraint) is specified for an otherwise non-strict expectation, then this constraint will always be implicitly verified at the end of the test. Therefore, explicitly verifying such an expectation inside the full verification block is not necessary.
So, we have seen how to do unordered verifications with Verifications
,
ordered verifications with VerificationsInOrder
, and full verifications
with FullVerifications
.
But what about full ordered verifications? Easy enough:
@Test
public void verifyAllInvocationsInOrder(final Dependency mock)
{
// Code under test included here for easy reference:
mock.setSomething(123);
mock.setSomethingElse("anotherValue");
mock.setSomething(45);
mock.save();
new FullVerificationsInOrder()
{{
mock.setSomething(anyInt);
mock.setSomethingElse(anyString);
mock.setSomething(anyInt);
mock.save();
}};
}
Notice there is a not so obvious difference in semantics, though.
In the verifyAllInvocations
test above, we were able to match two separate
mock.setSomething(...)
invocations with a single invocation in the verification block.
In the verifyAllInvocationsInOrder
test, however, we had to write two separate
invocations to that method inside the block, in the proper order with respect to other invocations.
You may now be thinking that writing a FullVerificationsInOrder
block ends up being
the same as writing an Expectations
block where all expectations are strict.
So, have we come full circle? Almost, but not quite.
For non-strict expectations, the default invocation count constraint corresponds to a
minTimes = 1
assignment, which leaves room for multiple invocations to the
same method or constructor in the replay phase.
So, in the above test for example, if the setSomethingElse(...)
method was invoked
a second time during the replay phase, the test would still pass (provided the second invocation
occurred in the expected order, as specified inside the verification block).
By default, all invocations to all mocked instances/types in effect for a
given test must be verified explicitly when using a new FullVerifications() {}
or
new FullVerificationsInOrder() {}
block.
Now, what if we have a test with two (or more) mocked types but we only want to fully verify
invocations to one of them (or to any subset of mocked types when more than two)?
The answer is to use the FullVerifications(Object... mockedTypesAndInstancesToVerify)
constructor, where only the given mocked instances and mocked types (ie, class objects/literals) are considered.
The following test provides an example.
@Test
public void verifyAllInvocationsToOnlyOneOfTwoMockedTypes(Dependency mock1, AnotherDependency mock2)
{
// Inside code under test:
mock1.prepare();
mock1.setSomething(123);
mock2.doSomething();
mock1.editABunchMoreStuff();
mock1.save();
new FullVerifications(mock1)
{{
mock1.prepare();
mock1.setSomething(anyInt);
mock1.editABunchMoreStuff();
mock1.save(); times = 1;
}};
}
In the test above, the mock2.doSomething()
invocation is never verified.
It's possible to restrict verification only to the methods (and constructors) of a single class,
by passing its class literal in the FullVerifications(...)
or FullVerificationsInOrder(...)
constructor.
For example, the new FullVerificationsInOrder(AnotherDependency.class) { ... }
block would only make
sure that all invocations to the mocked AnotherDependency
class were verified.
To verify that no invocations at all occurred on the non-strict mocked types/instances used in a test, add
an empty full verification block to it.
As always, note that any expectations that were recorded as expected through an specified
times/minTimes
constraint are verified implicitly and therefore disregarded by the full verification
block; in such a case the empty verification block will verify that no other invocations occurred.
Additionally, if any expectations were verified in a previous verification block in the same test, they are
also disregarded by the full verification block.
If the test uses two or more mocked types/instances and you want to verify that no invocations occurred for some of them, specify the desired mocked types and/or instances in the constructor to the empty verification block. An example test follows.
@Test
public void verifyNoInvocationsOnOneOfTwoMockedDependenciesBeyondThoseRecordedAsExpected(
final Dependency mock1, final AnotherDependency mock2)
{
new NonStrictExpectations()
{{
// These two are recorded as expected:
mock1.setSomething(anyInt); minTimes = 1;
mock2.doSomething(); times = 1;
}};
// Inside code under test:
mock1.prepare();
mock1.setSomething(1);
mock1.setSomething(2);
mock1.save();
mock2.doSomething();
// Will verify that no invocations other than to "doSomething()" occurred on mock2:
new FullVerifications(mock2) {};
}
A full verification block (ordered or not) also allows us to verify that certain methods and/or constructors never
get invoked, without having to specify each one of them with a corresponding times = 0
assignment.
The following test provides an example.
@Test
public void readOnlyOperation(final Dependency mock)
{
new NonStrictExpectations()
{{
mock.getData(); result = "test data";
}};
// Code under test:
String data = mock.getData();
// mock.save() should not be called here
...
new FullVerifications()
{{
mock.getData(); minTimes = 0; // calls to getData are allowed
}};
}
If a call to any method (or constructor) of the Dependency
class occurs during the
replay phase, except for the ones explicitly verified in the verification block
(Dependency#getData()
in this case), then the test above will fail.
On the other hand, it may be easier to use strict expectations in such cases, without any verification block at all.
There is one last thing about verification blocks we need to examine: the ability to easily verify invocations that occur inside loops, for an specified number of iterations of the loop.
@Test
public void verifyAllInvocations(final Dependency mock)
{
int numberOfIterations = 3;
// Code under test included here for easy reference:
for (int i = 0; i < numberOfIterations; i++) {
DataItem data = getData(i);
mock.setData(data);
mock.save();
}
new Verifications(numberOfIterations)
{{
mock.setData((DataItem) withNotNull());
mock.save();
}};
new VerificationsInOrder(numberOfIterations)
{{
mock.setData((DataItem) withNotNull());
mock.save();
}};
}
The use of two verification blocks above is just to explain the different semantics between
ordered and unordered iterating verification blocks.
In the first block, each verified invocation will have to match at least three invocations to the
same method in the replay phase, because this was the number of iterations passed in the constructor.
For an unordered iterating block, the specified number of iterations is effectively multiplied by
the lower and upper invocation count limits; this happens even if an explicit constraint is
specified inside the block, such as a minTimes = 1; maxTimes = 4;
pair of assignments, which in this particular example would be turned into
minTimes = 3; maxTimes = 12;
.
In the second block, on the other hand, invocation count constraints are not affected.
Instead, the resulting effect is equivalent to "unrolling the loop", as if the whole sequence of
verified invocations inside the block was duplicated for each iteration.
The semantics for an iterating FullVerifications
block is the same as for a regular
Verifications
block.
The same applies for an iterating FullVerificationsInOrder
block, with respect to a
VerificationsInOrder
block.
We have seen how to record results for invocations through assignments to the
result
field or calls to the returns(...)
methods.
We have also seen how to match invocation arguments flexibly with the withXyz(...)
group of methods and the various anyXyz
fields.
But what if a test needs to decide the result of a recorded invocation based on the arguments it
will receive at replay time?
We can do it through a mockit.Delegate
instance, as exemplified below.
@Test
public void someTestMethod()
{
new Expectations()
{
@NonStrict DependencyAbc abc;
{
abc.intReturningMethod(anyInt, null);
result = new Delegate()
{
// The name of this method can actually be anything.
int intReturningMethod(int i, String s)
{
assertTrue(i > 0);
assertEqual(i == 1 ? "one" : "other", s);
return i + 1;
}
};
}
};
new UnitUnderTest().doSomething();
}
The Delegate
interface is empty, being used simply to tell JMockit that actual
invocations at replay time should be delegated to the corresponding methods in the delegate object.
A corresponding method in the delegate implementation must have parameters matching the method
in the mocked type for which an invocation is being recorded.
The name of this delegate method can be different though, provided it is the only one
defined in the delegate implementation class.
If the class has two or more methods (with any modifiers), then one of them will have
to match both the name and the parameters of the corresponding recorded method.
Note that the return type of a delegate method does not have to be exactly the same, since it's
not part of the method signature. It should be compatible, though, otherwise a
ClassCastException
is likely.
Note also that this can de done for non-public
methods and even for
static
, final
, and native
mocked methods.
The following example test shows a constructor invocation being delegated in a reusable
Delegate
class, which saves an argument value for later verification in the test.
@Test
public void anotherTestMethod()
{
final ConstructorDelegate delegate = new ConstructorDelegate();
new Expectations()
{
Collaborator mock;
{
new Collaborator(anyInt); result = delegate;
}
};
new Collaborator(4);
assertTrue(delegate.capturedArgument > 0);
}
static class ConstructorDelegate implements Delegate
{
int capturedArgument;
void $init(int i) { capturedArgument = i; }
}
Constructors are also handled by delegate methods, except that such methods must be named "$init".
Delegate
implementations can be used to validate invocation arguments, but they are limited to
expectation blocks. Besides, the main point of delegate methods is to specify invocation results (values to
return or exceptions to throw) at replay time, based on the arguments received.
If the actual need is to validate the arguments passed at replay time in each invocation matching
an expectation, the forEachInvocation
field should be used instead.
Such validations can be specified not only in expectation blocks, but also in verification blocks.
For example, consider the following test:
@Test
public void verifyExpectationWithArgumentValidatorForEachInvocation(final Collaborator mock)
{
// Inside tested code:
new Collaborator().doSomething(true, new int[2], "test");
new Verifications()
{
{
mock.doSomething(anyBoolean, null, null);
forEachInvocation = new Object()
{
void validate(Boolean b, int[] i, String s)
{
assertTrue(b);
assertEquals(2, i.length);
assertEquals("test", s);
}
};
}
};
}
In this test, all invocations to the Collaborator#doSomething
method that occur during the replay phase
and that match the verified expectation will be validated by a call to the specified validate
method.
Each such call will be made with the same arguments that the verified method/constructor received at replay time.
In this particular example, the verified expectation matches invocations with any arguments, but
more strict argument matchers could have been specified.
Differently from Delegate
implementations, the object assigned to the forEachInvocation
field can be of any type.
The implementation class, however, should define exactly one non-private
method of any name, with the
same number of parameters as the validated method/constructor (any number of additional private
methods
is allowed).
The types of corresponding parameters don't have to be exactly the same, but they must be
compatible in order to avoid the potential for ClassCastException
's.
Optionally, a first parameter of type mockit.Invocation
can be declared in the
validation method, which should still have the remaining parameters. The semantics in this case
are the same as in the case of a Delegate
method with that same special parameter.
Normally, behavior-based tests for a given unit are written against the
public/protected/default
interface of the unit's dependencies.
Sometimes, however, the method being tested may call private
methods defined in the
same class, and accounting for the behavior of those methods in the test may be undesirable
(perhaps because it is too complex or simply not important for the test).
A different situation arises when a test wants to verify not only the behavior, but also the state of the unit under test after it is exercised, and the relevant state is stored in non-accessible fields. Some tests may also need to set some necessary state in non-accessible fields of the unit under test before it is exercised.
A third kind of situation would be the eventual need to instantiate non-accessible classes from a given test. Such a need should be rare, though.
To handle these needs (rare though they may be) the Expectations
class provides a
set of Reflection-based utility methods that allow a test to invoke non-accessible methods on a
given object or class, to instantiate objects through non-accessible constructors, and to get or
set the values of fields in given objects or classes.
The example test below showcases some of these utility methods.
@Test
public void someTestMethod()
{
final UnitUnderTest tested = new UnitUnderTest();
new Expectations()
{
@NonStrict DependencyAbc abc;
{
// Defines some necessary state on the unit under test:
setField(tested, "someIntField", 123);
// Expectations recorded (even if the invocations are done through Reflection):
newInstance("some.package.AnotherDependency", true, "test"); maxTimes = 1;
invoke(tested, "intReturningMethod", 45, ""); result = 1;
// other expectations recorded...
}
};
tested.doSomething();
String result = Deencapsulation.getField(tested, "result");
assertEquals("expected result", result);
}
The utility methods mentioned above are actually defined in the Invocations
base class,
and therefore they are also available to Verifications
subclasses.
This allows invocations to private methods and constructors to be verified in a verification block, just like they
can be recorded in an expectation block.
The mockit.Deencapsulation
class used at the end of the test is a separate utility
class which contains those same Reflection-based utilities.
It's a more generally useful class, since it can be called from any place in test code.
Its methods are all static
, so they can be statically imported for easier access.
In a test class, we declare mocked types through mock fields and mock parameters, sometimes using one of the
@Mocked
and @NonStrict
annotations, sometimes by
simply letting JMockit infer from the declaration scope if the field or parameter is to be mocked or not.
By default, in any such case all instance methods which can be called on the mock
field/parameter, and all constructors and static methods which can be called on the
mocked class and its super-classes (except for java.lang.Object
) will get mocked.
That is, by default we get a fully mocked type, be it an interface or a class of any kind.
Full mocking will be appropriate in most cases, but in some situations we might need to exclude some methods or constructors from being mocked. Alternatively, we might want to only mock a few specific methods/constructors. This is where partial mocking comes into the picture.
If for a given test a type is partially mocked, then it won't be possible to record nor verify expectations for non-mocked methods/constructors. When one of these methods/constructors is invoked during any of the three test phases (particularly the replay phase), the actual method/constructor body will be executed.
Methods and constructors to be mocked can be explicitly specified through the
@Mocked(methods = {"filter1", "filter2", ...})
annotation attribute.
Each filter value is composed of an optional regular expression (java.util.regex
)
that matches method names, followed by an also optional parenthesized list of parameter type names.
The following example test shows several ways to use partial mocking.
public class MyTestClass
{
@Mocked("nanoTime") final System system = null;
@Mocked("print") final JComponent component = new JButton();
@Test
public void staticPartialMocking(@Mocked(methods = "()", inverse = true) final Graphics graphics)
{
...
new Expectations()
{
@Mocked({"(int)", "doInternal()", "[gs]etValue", "complexOperation(Object)"})
Collaborator mock;
{
graphics.setClip(0, 0, 80, 60);
graphics.translate(-15, -12);
component.print(graphics);
mock.getValue();
}
};
...
}
}
For convenience, the @Mocked
annotation defines the default value
attribute as a synonym for the methods
attribute.
This is what allows us to write @Mocked("nanoTime")
, as shown above.
The inverse
attribute, which by default is equal to false
, inverts the
meaning of the specified mock filters.
For example, as @Mocked("nanoTime")
or
@Mocked(methods = "nanoTime", inverse = false)
cause only the
System#nanoTime()
method to be mocked, the inverse specification
@Mocked(methods = "nanoTime", inverse = true)
cause it to be the only
method not mocked in the java.lang.System
class.
To specify constructors through a mock filter expression, leave the first part (which corresponds to method names) empty and specify the constructor parameter type names between parentheses. Use commas to separate parameters, if more than one. The parameter type name actually can be any unique suffix of the fully qualified type name. In practice, this means that it's almost never necessary to specify any package names for a reference type.
Specifying parameter types in a filter expression that targets methods is possible, but usually unnecessary. It will only be required if the method is overloaded.
Finally, notice that when the mocked type is a class, a mock filter expression for methods will
actually match methods defined anywhere in the class hierarchy, from the mocked class up to
Object
(not itself included).
Static partial mocking has the inconvenience that we need to explicitly specify the methods/constructors to be mocked or not mocked, and do so inside strings instead of in Java code. In short, it entails extra work and is not "refactoring friendly".
An alternative that avoids both problems is to let JMockit figure out when to execute the real implementation of methods/constructors during the replay phase, based on which invocations were recorded in an expectation block and which were not. The following example tests demonstrate this feature, which we describe as dynamic partial mocking since the decision of what is mocked is made at runtime, as invocations to mocked types during the replay phase match invocations recorded in expectation blocks.
public final class DynamicPartialMockingTest
{
static class Collaborator
{
private final int value;
Collaborator() { value = -1; }
Collaborator(int value) { this.value = value; }
int getValue() { return value; }
final boolean simpleOperation(int a, String b, Date c) { return true; }
static void doSomething(boolean b, String s) { throw new IllegalStateException(); }
}
@Test
public void dynamicallyMockAClass()
{
new Expectations(Collaborator.class)
{{
new Collaborator().getValue(); result = 123;
}};
// Mocked:
Collaborator collaborator = new Collaborator();
assertEquals(123, collaborator.getValue());
// Not mocked:
assertTrue(collaborator.simpleOperation(1, "b", null));
assertEquals(45, new Collaborator(45).value);
}
@Test
public void dynamicallyMockAnInstance()
{
final Collaborator collaborator = new Collaborator(2);
new NonStrictExpectations(collaborator)
{{
collaborator.simpleOperation(1, "", null); result = false;
Collaborator.doSomething(anyBoolean, "test");
}};
// Mocked:
assertFalse(collaborator.simpleOperation(1, "", null));
Collaborator.doSomething(true, null);
// Not mocked:
assertEquals(2, collaborator.getValue());
assertEquals(45, new Collaborator(45).value);
assertEquals(-1, new Collaborator().value);
}
}
As shown above, the Expectations(Object...)
and NonStrictExpectations(Object...)
constructors accept one or more classes or objects to be partially mocked.
If the Class
object for a given class is passed, the methods and constructors
defined in that class are considered for mocking, but not the methods and constructors
of its super-class (and so on until Object
).
If an instance of a given class is passed, on the other hand, then all methods and constructors
defined in the whole class hierarchy, from the concrete class of the given instance up to (but
not including) Object
, are considered for mocking.
Notice that in these two example tests there is no mock field or mock parameter. This feature effectively provides yet another way to specify mocked types, which lets us turn objects stored in local variables into mocked instances. Such objects can be created with any amount of state in instance fields; they will keep that state after being mocked.
With regular mocking, invocations to mocked types or mock instances that occur during
replay time will never cause the real method/constructor implementation to be executed.
With dynamic mocking, on the other hand, whether the real implementation gets executed or not
depends on the existence of a recorded expectation that matches the invocation.
If such a matching expectation exists, the invoked method or constructor is still mocked,
preventing its real implementation to be executed. If no such expectation can be found for a
particular invocation at replay time, the real implementation gets executed.
This is a simple rule, but it can produce surprising results, specially when strict
expectations are recorded on a dynamic mock. For example, if you record a strict expectation on
a dynamically mocked object with a maximum invocation count of n (specified either
through the times
or maxTimes
field), then only the first n
invocations at replay time will match the expectation; the next invocation, if it occurs, will
cause the real method implementation to be executed, instead of causing the test to fail with an
"unexpected invocation" error.
It's also possible to pass the objects automatically created for mock fields or parameters into
those expectation block constructors.
The declaration of such dynamically mocked mock fields/parameters can make use of the
Mocked
annotation and any of its attributes.
We could even combine static and dynamic partial mocking for the same mocked class, although that
wouldn't probably be of much use.
Finally, dynamically mocked types can be freely verified inside verification blocks. Just like in expectation blocks, invocations to them will never execute the real implementation when inside the verification block.
When using complex APIs where functionality is distributed through many different objects, it is not uncommon to see
chained invocations of the form obj1.getObj2(...).getYetAnotherObj().doSomething(...)
.
In such cases it may be necessary to mock all objects/classes in the chain, starting with obj1
.
The @Cascading
annotation provides this ability.
Just like @Mocked
, it can be applied to mock fields and mock parameters.
Similarly to @NonStrict
and @Capturing
, the use of
@Cascading
on a mock field or test method parameter will imply that the type is
mocked (this doesn't preclude use of @Mocked
on the same field/parameter, however).
The following test shows a basic example, where the cascading mocked type is used in expectation
and verification blocks. The test involves use of the java.net
and java.nio
APIs.
@Test
public void recordAndVerifyExpectationsOnCascadedMocks(@Cascading final Socket mock)
throws Exception
{
new NonStrictExpectations()
{
InetSocketAddress ignored;
{
mock.getChannel().isConnected(); result = false;
}
};
// Inside production code:
Socket s = new Socket(...);
...
if (!s.getChannel().isConnected()) {
SocketAddress sa = new InetSocketAddress("remoteHost", 123);
s.getChannel().connect(sa);
}
...
new Verifications()
{
{
mock.getChannel().connect((SocketAddress) withNotNull());
}
};
}
In the test above, since the Socket
class was mocked with cascading, any calls to
methods like getChannel()
will return a cascaded mock object whenever they
occur during the test. The cascaded mock will allow further cascading, so a null
reference will never be obtained from methods which return object references (except for return
types Object
or String
which will return null
, or
collection types which will return a non-mocked empty collection).
By default, a new cascaded mock is created for each unique chain of method calls, starting from a
given cascading type. If necessary, this default mock can be replaced with a regular mock,
introduced though a mock field or parameter. To do so, assign the desired mock instance to the
result
field, right after the method invocation chain of interest.
Our discussion of this feature will be based on the (contrived) code below. Realistic examples can be found in the Timing Framework and Animated Transitions sample test suites, available with the full JMockit distribution.
public interface Service
{
int doSomething();
}
final class ServiceImpl implements Service
{
public int doSomething() { return 1; }
}
public final class TestedUnit
{
private final Service service1 = new ServiceImpl();
private final Service service2 = new Service()
{
public int doSomething() { return 2; }
};
Observable observable;
public int businessOperation(final boolean b)
{
new Callable() // Callable is a parameterized interface from java.util.concurrent
{
public Object call() { throw new IllegalStateException(); }
}.call();
observable = new Observable() // Observable is a concrete class from java.util
{{
if (b) {
throw new IllegalArgumentException();
}
}};
return service1.doSomething() + service2.doSomething();
}
}
The method we want to test, businessOperation(boolean)
, creates several new
instances of classes that implement public abstractions.
Most of these implementations are defined through anonymous inner classes, which are completely
inaccessible (except for the use of Reflection) from client code.
This kind of situation will probably not occur often in real projects, though. Still, we can write a test that captures such class definitions and instantiations as they happen during test execution, automatically mocking the implementation classes as they are loaded by the JVM. (As a matter of fact, classes that have been loaded previously will also get mocked for the duration of a given test, transparently and as needed.) The next test shows how it's done.
public final class UnitTest
{
@Mocked(capture = 10) Service service;
@Test
public void captureAllInternallyCreatedInstances(@Mocked(capture = 1) final Callable<?> callable)
throws Exception
{
Service initialMockService = service;
new NonStrictExpectations()
{
@Mocked(capture = 1) Observable observable;
{
service.doSomething(); returns(3, 4);
}
};
TestedUnit unit = new TestedUnit();
int result = unit.businessOperation(true);
assertNotNull(unit.observable);
assertNotSame(initialMockService, service);
assertEquals(7, result);
new Verifications() {{ callable.call(); }};
}
}
Note that we used all three possible scopes for mocked types: a mock field of the test class, a
mock parameter of the test method, and a local mock field of the expectation block.
In all three cases the mocked type is either an interface or a non-final
class, and
the capturing
annotation attribute has been used.
This optional attribute of the Mocked
annotation takes an int
value
that specifies the maximum number of instantiations of classes assignable to the declared mocked
type that should be captured.
For a non-final
mock field, each captured instance will be immediately assigned to
the field, up to the specified maximum number of instances.
If any more instantiations occur they won't be assigned to the field, even though the classes to
which such instances belong will still get mocked.
However, if there is a second capturing field of the same mocked type, then those extra instances
will get assigned to it up to the its maximum number of instances to capture.
So, once a mocked type is declared to be captured, all implementation classes will get mocked for
the test, no matter how many new instances are captured.
For a mock parameter, on the other hand, new instances will never get assigned to the parameter,
so any positive value for the capture
attribute will have the same effect (this
limitation may be lifted in a future version, for non-final
parameters).
Finally, notice that it is perfectly valid to record and/or verify invocations to the captured mocked types, as exemplified in the expectation and verification blocks above.
The simplest form of test code reuse with JMockit is the declaration of mock fields at the test
class level.
As the next example shows, the objects that are automatically created and assigned to such fields
(when they aren't declared to be final
, that is) can be used in any number of test
methods.
(The complete source code for this example can be found under "mockit/samples/LoginService", in
the full distribution.)
public final class LoginServiceTest
{
@Mocked UserAccount account;
LoginService service;
@Before
public void init()
{
service = new LoginService();
new NonStrictExpectations()
{{
UserAccount.find("john"); result = account;
}};
}
@Test
public void setAccountToLoggedInWhenPasswordMatches() throws Exception
{
willMatchPassword(true);
service.login("john", "password");
new Verifications()
{{
account.setLoggedIn(true);
}};
}
private void willMatchPassword(final boolean match)
{
new NonStrictExpectations()
{{
account.passwordMatches(anyString); result = match;
}};
}
@Test
public void notSetAccountLoggedInIfPasswordDoesNotMatch() throws Exception
{
willMatchPassword(false);
service.login("john", "password");
new Verifications()
{{
account.setLoggedIn(true); times = 0;
}};
}
// other tests that use the "account" mock field
}
In the above test class, we have two instance fields, one of them a mock field that is assigned automatically by JMockit for each test, and the other a regular non-mock field which is assigned manually in a test setup method.
The tests in this example test class exercise the
LoginService#login(String accountId, String password)
method (our unit under test).
This method first attempts to look up an existing user account from the given login name
("accountId", which is expected to be unique among all accounts).
Since several different tests are needed to fully exercise this unit, a non-strict invocation to
the UserAccount#find(String accountId)
method is recorded for all tests in the
class, with an specific login name ("john") and the mock account object as the value to be returned.
Remember, any given test can use multiple expectation and/or verification blocks.
And such blocks can even be written inside shared "before" and "after" methods, respectively.
Since the object assigned to a mock field of the test class is available anywhere in the
class, not just inside expectation/verification blocks, there is the question of just what
happens as a consequence of such invocations, if any occur.
The answer is that such invocations are freely allowed, and in the case of
non-void
methods the invocation will return the default value according to the
method's return type (0
for primitive integers, empty collections and arrays, and so on).
Another form or reuse exemplified above is shown by the willMatchPassword(boolean)
method, which contains another reusable expectation block.
In this case, an invocation to the UserAccount#passwordMatches(String)
method is
recorded for any password value, with the resulting return value provided as a parameter to the reusable method.
Yet another form of reuse for expectation and verification blocks is to create named subclasses instead of anonymous
ones.
For example, instead of having the willMatchPassword(boolean)
method we could have a reusable inner
class:
final class PasswordMatching extends NonStrictExpectations
{
PasswordMatching(boolean match)
{
account.passwordMatches(anyString); result = match;
}
}
@Test
public void setAccountToLoggedInWhenPasswordMatches() throws Exception
{
new PasswordMatching(true);
...
}
It's important that such classes be declared as final
, unless they are intended
to be used as base classes for further extension inside individual test methods.
They can also be static nested classes and even top-level public classes, and therefore reused in
any number of separate test classes.