Skip to content
Commits on Source (44)
<?xml version="1.0" encoding="UTF-8"?>
<fileset-config file-format-version="1.2.0" simple-config="false">
<local-check-config name="mockito-code" location="conf/checkstyle-code.xml" type="project" description="">
<additional-data name="protect-config-file" value="false"/>
</local-check-config>
<local-check-config name="mockito-test" location="conf/checkstyle-test.xml" type="project" description="">
<additional-data name="protect-config-file" value="false"/>
</local-check-config>
<fileset name="mockito-code" enabled="true" check-config-name="mockito-code" local="true">
<file-match-pattern match-pattern="^src[/\\].*java$" include-pattern="true"/>
</fileset>
<fileset name="mockito-test" enabled="true" check-config-name="mockito-test" local="true">
<file-match-pattern match-pattern="^test[/\\].*java$" include-pattern="true"/>
</fileset>
</fileset-config>
<?xml version="1.0" encoding="UTF-8"?>
<fileset-config file-format-version="1.2.0" simple-config="false">
<local-check-config name="mockito-code" location="conf/checkstyle-code.xml" type="project" description="">
<additional-data name="protect-config-file" value="false"/>
</local-check-config>
<local-check-config name="mockito-test" location="conf/checkstyle-test.xml" type="project" description="">
<additional-data name="protect-config-file" value="false"/>
</local-check-config>
<fileset name="mockito-code" enabled="true" check-config-name="mockito-code" local="true">
<file-match-pattern match-pattern="^src[/\\].*java$" include-pattern="true"/>
</fileset>
<fileset name="mockito-test" enabled="true" check-config-name="mockito-test" local="true">
<file-match-pattern match-pattern="^test[/\\].*java$" include-pattern="true"/>
</fileset>
</fileset-config>
root = true
[*]
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
indent_style = space
indent_size = 4
# Auto detect text files and perform LF normalization
* text=auto
# Allow gradle.bat to retain CRLF
gradlew.bat text eol=crlf
......@@ -3,6 +3,8 @@
*.ipr
*.iws
.idea
*.eml
.shelf
# Eclipse
.classpath
......@@ -17,3 +19,4 @@ out
.gradle
classes
.gradletasknamecache
*.log
# More details on how to configure the Travis build
# https://docs.travis-ci.com/user/customizing-the-build/
# Speed up build by leveraging travis caches
cache:
directories:
- $HOME/.gradle/caches/
- $HOME/.gradle/wrapper/
# Enabling container based infrastructure hoping it will help the build speed <= this didn't work well, so it's reverted
# see https://docs.travis-ci.com/user/migrating-from-legacy/ and https://docs.travis-ci.com/user/ci-environment
sudo: true
language: java
jdk:
- oraclejdk7
env:
matrix:
- TERM=dumb
global:
- secure: ZjU6SpkLzTAJr9qmxKDSI0uA8eJ/r5n58/equD6ifDlCBUasxPxOwaIARuNjhH45UCFOQDO9HMmvD7IWufyYl0OpACMM6MZ/0JX5Qsd+vhmBGirl6H3rRbVpvyoSI1J2xqJXy9/yTU54IYMDv3R7suinvmKXYHCqJ3h7ke+m4Ik=
- secure: SDwSEK8W+GU78fVLi+P0k+v5eYK1fevz1Z0Htsjta2PRr0DicL6CMTNLxi48c3vXT+GHL6W8uojmfRwnHd8yyRZu2nW4Hda5rWB3de6Nz64lOZFYUbvoZfj9TdCgDYn+u2jUkm6+C76ZlPtfQhS97uZCb9iCDSdm1JErpng5e6g=
- secure: aRk3elhhgDvXc2RyKAOcn9UF4w5U2zgFqUEEwdZ/r5DLrlKlA0aDE3pBZhST479nHIVEjF3w/SjePmfc9K/JPp2cLE12qHBT5mp4F2MZhNkBDay4vsXLwkhWsyQLz85VrvR/QkeCbLXSQBCZsy/KI8PwwMIrcEH6rAoo+1MYTos=
matrix:
include:
- jdk: oraclejdk8
- jdk: oraclejdk8
env: SKIP_RELEASE=true MOCK_MAKER=mock-maker-inline
- jdk: oraclejdk9
env: SKIP_RELEASE=true
- jdk: oraclejdk9
env: SKIP_RELEASE=true MOCK_MAKER=mock-maker-inline
- jdk: oraclejdk9
env: SKIP_RELEASE=true SIMULATE_JAVA11=true
- install: . ./install-jdk.sh -F 10 -L GPL
env: SKIP_RELEASE=true JDK='Oracle JDK 10'
- install: . ./install-jdk.sh -F 10 -L GPL
env: SKIP_RELEASE=true MOCK_MAKER=mock-maker-inline JDK='Oracle JDK 10'
- install: . ./install-jdk.sh -F 11 -L BCL
env: SKIP_RELEASE=true JDK='Oracle JDK 11'
- install: . ./install-jdk.sh -F 11 -L BCL
env: SKIP_RELEASE=true MOCK_MAKER=mock-maker-inline JDK='Oracle JDK 11'
allow_failures:
- env: SKIP_RELEASE=true JDK='Oracle JDK 11'
- env: SKIP_RELEASE=true MOCK_MAKER=mock-maker-inline JDK='Oracle JDK 11'
branches:
#Don't build tags
except:
- /^v\d/
before_install:
- wget https://raw.githubusercontent.com/sormuras/bach/master/install-jdk.sh
#Below skips the installation step completely (https://docs.travis-ci.com/user/customizing-the-build/#Skipping-the-Installation-Step)
#We need it because otherwise Travis CI injects an awkward './gradlew assemble' step into the CI workflow
#We want to control and decide what Gradle tasks are executed
install:
- true
- true
script:
- ./gradlew ciBuild
# We are using && below on purpose
# ciPerformRelease must run only when the entire build has completed
# This guarantees that no release steps are executed when the build or tests fail
- ./gradlew build idea -s -PcheckJavaCompatibility && ./gradlew ciPerformRelease
after_success:
- ./gradlew release
- ./gradlew cobertura coveralls
#Generates coverage report:
- ./gradlew --stacktrace coverageReport && cp build/reports/jacoco/mockitoCoverage/mockitoCoverage.xml jacoco.xml || echo "Code coverage failed"
- bash <(curl -s https://codecov.io/bash) || echo "Codecov did not collect coverage reports"
> gradlew build
\ No newline at end of file
Mockito license - MIT.
Libraries used:
Cglib - Apache License 2.0
ASM - BSD license
Mockito all distribution:
Objenesis - MIT license
Hamcrest - BSD license
\ No newline at end of file
![Mockito](http://docs.mockito.googlecode.com/hg/latest/org/mockito/logo.jpg)
simplier & better mocking
<a href="http://site.mockito.org">
<img src="https://raw.githubusercontent.com/mockito/mockito/master/src/javadoc/org/mockito/logo.png"
srcset="https://raw.githubusercontent.com/mockito/mockito/master/src/javadoc/org/mockito/logo@2x.png 2x"
alt="Mockito" />
</a>
[![Build Status](https://travis-ci.org/mockito/mockito.svg?branch=master)](https://travis-ci.org/mockito/mockito) [![Coverage Status](http://img.shields.io/coveralls/mockito/mockito/master.svg)](https://coveralls.io/r/mockito/mockito) [ ![Current release](https://api.bintray.com/packages/szczepiq/maven/mockito/images/download.svg) ](https://bintray.com/szczepiq/maven/mockito/_latestVersion) [![Maven Central](https://maven-badges.herokuapp.com/maven-central/org.mockito/mockito-core/badge.svg)](https://maven-badges.herokuapp.com/maven-central/org.mockito/mockito-core)
Most popular mocking framework for Java
## Current release
See the [release notes page](https://github.com/mockito/mockito/blob/master/doc/release-notes/official.md) and [latest documentation](http://mockito.github.io/mockito/docs/current/org/mockito/Mockito.html).
[![Build Status](https://travis-ci.org/mockito/mockito.svg?branch=release/2.x)](https://travis-ci.org/mockito/mockito) [![Coverage Status](https://img.shields.io/codecov/c/github/mockito/mockito.svg)](https://codecov.io/github/mockito/mockito) [![MIT License](http://img.shields.io/badge/license-MIT-green.svg) ](https://github.com/mockito/mockito/blob/master/LICENSE)
## JDK8 status
[![latest release](https://img.shields.io/badge/release%20notes-2.x-yellow.svg)](https://github.com/mockito/mockito/blob/release/2.x/doc/release-notes/official.md)
[![Bintray](https://api.bintray.com/packages/mockito/maven/mockito-development/images/download.svg)](https://bintray.com/mockito/maven)
[![Maven Central](https://img.shields.io/maven-central/v/org.mockito/mockito-core.svg)](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.mockito%22%20AND%20a%3A%22mockito-core%22)
[![Javadocs](http://www.javadoc.io/badge/org.mockito/mockito-core.svg?color=red)](http://www.javadoc.io/doc/org.mockito/mockito-core)
Mockito should work fine with JDK8 if you stay away from _default methods_ (aka _defender methods_). Lambda usage may work just as good for `Answer`s. We're unsure about every JDK8 features at the moment, like serializing a mock that uses a lambda. Error report and pull request are welcome though ([contributing guide](https://github.com/mockito/mockito/wiki/How%20To%20Contribute)).
## Moving to github
We are currently moving a few stuff from [Google Code](https://code.google.com/p/mockito/) to [Github](https://github.com/mockito/mockito).
## Current version is 2.x
Still on Mockito 1.x? See [what's new](https://github.com/mockito/mockito/wiki/What%27s-new-in-Mockito-2) in Mockito 2!
For now only the code repository is moved, other stuff will follow like the wiki pages. Documentation may or may not follow. But discussion group, issue tracker will stay at google (unfortunatley GH PR counters incremented before we had the chance to move our issues).
Mockito [continuously delivers](https://github.com/mockito/mockito/wiki/Continuous-Delivery-Overview) improvements using Shipkit library (http://shipkit.org). See the [latest release notes](https://github.com/mockito/mockito/blob/release/2.x/doc/release-notes/official.md) and [latest documentation](http://javadoc.io/page/org.mockito/mockito-core/2/org/mockito/Mockito.html). Docs in javadoc.io are available 24h after release. Read also about [semantic versioning in Mockito](https://github.com/mockito/mockito/wiki/Semantic-Versioning).
## Why drink it?
Mockito is a mocking framework that tastes really good. It lets you write beautiful tests with clean & simple API. Mockito doesn't give you hangover because the tests are very readable and they produce clean verification errors. Read more about [features & motivations](https://code.google.com/p/mockito/wiki/FeaturesAndMotivations).
Older 1.x releases are available in
[Central Repository](http://search.maven.org/#artifactdetails|org.mockito|mockito-core|1.10.19|jar)
, [Bintray](https://bintray.com/mockito/maven/mockito/1.10.19/view)
and [javadoc.io](http://javadoc.io/page/org.mockito/mockito-core/1.10.19/org/mockito/Mockito.html) (documentation).
> *"We decided during the main conference that we should use JUnit 4 and Mockito because we think they are the future of TDD and mocking in Java"* - Dan North, the originator of BDD
## More information
[More quotes](https://code.google.com/p/mockito/wiki/Quotes)
All you want to know about Mockito is hosted at [The Mockito Site](http://site.mockito.org) which is [Open Source](https://github.com/mockito/mockito.github.io) and likes [pull requests](https://github.com/mockito/mockito.github.io/pulls), too.
> Over 15000 downloads of 1.9.0 version ('12), excluding maven/Gradle users. For latest figures see the downloads.
Want to contribute? Take a look at the [Contributing Guide](https://github.com/mockito/mockito/blob/release/2.x/.github/CONTRIBUTING.md).
[More about the user base](https://code.google.com/p/mockito/wiki/UserBase)
Enjoy Mockito!
## How do I drink it?
## Need help?
Recommended way of getting Mockito is declaring a dependency on "mockito-core" library (not "mockito-all"!) using your favorite build system. My favorite build system happens to be [Gradle](http://gradle.org) and so I do:
* Search / Ask question on [stackoverflow](http://stackoverflow.com/questions/tagged/mockito)
* Go to the [mockito mailing-list](http://groups.google.com/group/mockito) (moderated)
* Open a ticket in GitHub [issue tracker](https://github.com/mockito/mockito/issues)
```groovy
repositories {
jcenter()
}
## How to develop Mockito?
dependencies {
testCompile "org.mockito:mockito-core:1.+"
}
```
To build locally:
For legacy builds with manual dependency management it might be useful to use mockito-all package that can be downloaded from [Mockito's Bintray repository](https://bintray.com/szczepiq/maven/mockito/_latestVersion) or [Bintray's jcenter](http://jcenter.bintray.com/org/mockito/mockito-all).
./gradlew build
For more information please refer to the [wiki page](https://code.google.com/p/mockito/wiki/DeclaringMockitoDependency).
To develop in IntelliJ IDEA you can use built-in Gradle import wizard in IDEA.
Alternatively generate the importable IDEA metadata files using:
### Then you can verify interactions
./gradlew idea
```java
import static org.mockito.Mockito.*;
Then, _open_ the generated *.ipr file in IDEA.
// mock creation
List mockedList = mock(List.class);
## How to release new version?
// using mock object ; observe that it didn't throw any "unexpected interaction exception" exception
mockedList.add("one");
mockedList.clear();
Mockito [implements Continuous Delivery model](https://github.com/mockito/mockito/wiki/Continuous-Delivery-Overview).
Every change on main branch (for example merging a pull request) triggers a release build on Travis CI.
The build publishes new version if specific criteria are met: all tests green, no 'ci skip release' used in commit message, see the build log for more information.
Every new version is published to ["mockito/maven" Bintray repository](https://bintray.com/mockito/maven).
New versions that Mockito team deems "notable" are additionally published to [Maven Central](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22org.mockito%22) and [JCenter](https://bintray.com/bintray/jcenter).
We used to publish every version to Maven Central but we changed this strategy based on feedback from the community ([#911](https://github.com/mockito/mockito/issues/911)).
// selective & explicit verification
verify(mockedList).add("one");
verify(mockedList).clear();
```
* Q: What's new in Mockito release model?
### Or stub method calls
A: In Q2 2017 we implemented [Mockito Continuous Delivery Pipeline 2.0](https://github.com/mockito/mockito/issues/911).
Not every version is published to Maven Central.
```java
// you can mock concrete classes, not only interfaces
LinkedList mockedList = mock(LinkedList.class);
* Q: How to publish to Maven Central?
// stubbing; before the actual execution
when(mockedList.get(0)).thenReturn("first");
A: Include "[ci maven-central-release]" in the **merge** commit when merging the PR.
**Hint**: To signify a new feature consider updating version to next minor/major, like: "2.8.0", "2.9.0", "3.0.0".
// the following prints "first"
System.out.println(mockedList.get(0));
* Q: How to promote already released version to a notable version?
// the following prints "null" because get(999) was not subbed
System.out.println(mockedList.get(999));
```
### You can go further
[Main reference documentation](http://mockito.github.io/mockito/docs/current/org/mockito/Mockito.html) features:
* [`mock()`](http://mockito.github.io/mockito/docs/current/org/mockito/Mockito.html#mock(java.lang.Class))/[`@Mock`](http://mockito.github.io/mockito/docs/current/org/mockito/Mock.html): Create a mock (specify how it should behave via [`Answer`](http://mockito.github.io/mockito/docs/current/org/mockito/Mockito.html#field_summary)/[`ReturnValue`](http://mockito.github.io/mockito/docs/current/org/mockito/ReturnValues.html)/[`MockSettings`](http://mockito.github.io/mockito/docs/current/org/mockito/MockSettings.html))
* [`when()`](http://mockito.github.io/mockito/docs/current/org/mockito/Mockito.html#when(T))/[`given()`](https://mockito.github.io/mockito/docs/current/org/mockito/BDDMockito.html#given(T)) to specify how a mock should behave.
* If the provided answers doesn't fit your needs, write one yourself extending the [`Answer`](http://mockito.github.io/mockito/docs/current/org/mockito/stubbing/Answer.html) interface
* [`spy()`](http://mockito.github.io/mockito/docs/current/org/mockito/Mockito.html#spy(T))/[`@Spy`](http://mockito.github.io/mockito/docs/current/org/mockito/Spy.html): Calls a real object but records what has been called,
* [`@InjectMocks`](http://mockito.github.io/mockito/docs/current/org/mockito/InjectMocks.html): Used as a kind of simple automatic dependency injection of fields created using the `@Spy` or `@Mock` annotation.
* [`verify()`](http://mockito.github.io/mockito/docs/current/org/mockito/Mockito.html#verify(T)) to check methods were called with given arguments; can match any expression via the [`any()`](https://mockito.github.io/mockito/docs/current/org/mockito/Matchers.html#any()), or capture what arguments where called using [`@Captor`](http://mockito.github.io/mockito/docs/current/org/mockito/Captor.html) instead.
* Try BDD syntax with [BDDMockito](http://mockito.github.io/mockito/docs/current/org/mockito/BDDMockito.html)
* Try the Mockito on Android, thanks to the Google guys working on dexmaker (more on that later)
### Remember
* Do not mock types you don't own
* Don't mock value objects
* Don't mock everything
* Show some love with your tests
Click [here](http://mockito.github.io/mockito/docs/current/org/mockito/Mockito.html) for more documentation and examples. Remember all documentation lives in javadocs so you don’t need to visit that page too often. You can grab the RefCard [here](http://refcardz.dzone.com/refcardz/mockito).
If you have any suggestions, find documentation unclear or you found a bug, write to our [mailing list](http://groups.google.com/group/mockito). You can report bugs [here](http://code.google.com/p/mockito/issues/list).
## Who is your bartender?
Mockito is served to you by **Szczepan Faber and friends**. First people who tried Mockito were developers of the [Guardian](http://guardian.co.uk/) project in London in early 2008. Here is how Szczepan explained [why we need another mocking framework](http://monkeyisland.pl/2008/01/14/mockito)?
Firstly, hats down before **[EasyMock](http://easymock.org/) folks** for their ideas on beautiful and refactorable mocking syntax. First hacks on Mockito were done on top of the EasyMock code.
Here are just some of my friends who contributed ideas to Mockito (apologize if I missed somebody): **Igor Czechowski**, **Patric Fornasier**, **Jim Barritt**, **Felix Leipold**, **Liz Keogh**, **Bartosz Bańkowski**.
Now some other people joined the gang : **Brice Dutheil** then **David Wallace**.
Special thanks to **Erik Ramfelt**, and **Steve Christou** for putting Mockito on there Jenkins server (continuous integration) for a few years. Now Travis and Coveralls took over.
Thanks to **Karol Poźniak** for the logo :)
Finally, thanks to **Erik Brakkee** who helps us getting jars to maven central
## links wrap-up
### Wiki
* [FAQ](https://github.com/mockito/mockito/wiki/FAQ)
* [How to contribute](https://github.com/mockito/mockito/wiki/How%20To%20Contribute)
* [Mockito for python](https://code.google.com/p/mockito/wiki/MockitoForPython)
* [Mockito VS EasyMock](https://code.google.com/p/mockito/wiki/MockitoVSEasyMock)
* [Related projects](https://code.google.com/p/mockito/wiki/RelatedProjects)
* [Release notes](https://github.com/mockito/mockito/blob/master/doc/release-notes/official.md)
* [More wiki pages](https://github.com/mockito/mockito/wiki)
* [Old wiki pages on google code](https://code.google.com/p/mockito/w/list)
### Blogs
* [Szczepan's new blog](http://szczepiq.blogspot.com/)
* [Brice's French coffee workshop](http://blog.arkey.fr/)
### Other project links
* [Latest documentation](http://mockito.github.io/mockito/docs/current/org/mockito/Mockito.html)
* [Dzone Reference Card](http://refcardz.dzone.com/refcardz/mockito)
* [Continuous integration server](http://travis-ci.org/mockito/mockito)
### Groups
* [Mockito mailing list](http://groups.google.com/group/mockito)
A: It isn't automated at the moment. [What's the use case?](https://github.com/mockito/mockito/issues/911)
<!--
Copyright (c) 2007 Mockito contributors
This program is made available under the terms of the MIT License.
-->
<project name="mockito" basedir=".">
<loadproperties srcfile="version.properties" />
<path id="ant.classpath">
<fileset dir="lib/build" includes="*bnd*" />
</path>
<property name="jar.core.path" value="build/libs/mockito-core-${version}.jar"/>
<property name="jar.all.path" value="build/libs/mockito-all-${version}.jar"/>
<taskdef resource="aQute/bnd/ant/taskdef.properties" classpathref="ant.classpath"/>
<target name="bndCore">
<delete file="${jar.core.path}.bnd"/>
<bnd
classpath="${jar.core.path}"
eclipse="false"
failok="false"
exceptions="true"
sourcepath="src"
destfile="${jar.core.path}.bnd"
files="conf/mockito-core.bnd"/>
</target>
<target name="bndAll">
<delete file="${jar.all.path}.bnd"/>
<bnd
classpath="${jar.all.path}"
eclipse="false"
failok="false"
exceptions="true"
sourcepath="src"
destfile="${jar.all.path}.bnd"
files="conf/mockito-all.bnd"/>
</target>
<target name="osgify.mockito-core" depends="bndCore">
<zip update="true" destfile="${jar.core.path}" >
<zipfileset src="${jar.core.path}.bnd" >
<include name="META-INF/MANIFEST.MF"/>
</zipfileset>
</zip>
</target>
<target name="osgify.mockito-all" depends="bndAll">
<zip update="true" destfile="${jar.all.path}">
<zipfileset src="${jar.all.path}.bnd" >
<include name="META-INF/MANIFEST.MF"/>
</zipfileset>
</zip>
</target>
</project>
buildscript {
repositories {
mavenLocal() //for local testing of mockito-release-tools
jcenter()
maven { url "https://plugins.gradle.org/m2/" }
}
dependencies {
classpath 'net.saliman:gradle-cobertura-plugin:2.0.0' // coveralls plugin depends on cobertura plugin
classpath 'org.kt3k.gradle.plugin:coveralls-gradle-plugin:0.6.1'
classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.0' //publishing to bintray
classpath 'org.codehaus.groovy.modules.http-builder:http-builder:0.5.2' //rest calls to bintray api
}
}
apply plugin: 'maven-publish'
classpath 'gradle.plugin.nl.javadude.gradle.plugins:license-gradle-plugin:0.14.0'
classpath 'ru.vyarus:gradle-animalsniffer-plugin:1.4.4' //for 'java-compatibility-check.gradle'
classpath 'net.ltgt.gradle:gradle-errorprone-plugin:0.0.15'
apply from: 'gradle/version.gradle'
apply from: "gradle/ide.gradle"
apply from: 'gradle/coverage.gradle'
allprojects {
repositories {
jcenter()
//Using buildscript.classpath so that we can resolve shipkit from maven local, during local testing
classpath 'org.shipkit:shipkit:2.0.28'
}
}
group = 'org.mockito'
description = 'Core API and implementation.'
sourceCompatibility = 1.5
targetCompatibility = 1.5
configurations {
provided
testUtil //TODO move to separate project
plugins {
id 'com.gradle.build-scan' version '1.15.1'
}
sourceSets {
main {
java.srcDir 'src'
compileClasspath = compileClasspath + configurations.provided
}
test {
java.srcDir 'test'
compileClasspath = compileClasspath + configurations.provided
}
}
description = 'Mockito mock objects library core API and implementation'
test.include "**/*Test.class"
apply plugin: 'base'
archivesBaseName = "mockito-core"
tasks.withType(JavaCompile) {
options.warnings = false
apply plugin: "org.shipkit.java"
allprojects {
plugins.withId("java") {
//Only upload specific modules we select
bintrayUpload.enabled = false
}
}
//TODO we should remove all dependencies to checked-in jars and move the 'mockito-all' project out
//we should consider getting rid of mockito-all completely (or moving out into a completely separate project.
dependencies {
provided "junit:junit:4.10"
compile "org.hamcrest:hamcrest-core:1.1", "org.objenesis:objenesis:2.1"
compile fileTree('lib/repackaged') { exclude '*.txt'}
apply from: 'gradle/root/ide.gradle'
apply from: 'gradle/root/gradle-fix.gradle'
apply from: 'gradle/root/java-compatibility-check.gradle'
apply from: 'gradle/java-library.gradle'
apply from: 'gradle/license.gradle'
apply from: 'gradle/root/coverage.gradle'
testCompile fileTree("lib/test")
testRuntime configurations.provided
apply from: 'gradle/mockito-core/inline-mock.gradle'
apply from: 'gradle/mockito-core/osgi.gradle'
apply from: 'gradle/mockito-core/javadoc.gradle'
apply from: 'gradle/mockito-core/testing.gradle'
testUtil sourceSets.test.output
}
apply from: 'gradle/dependencies.gradle'
def licenseFiles = copySpec {
//mockito license
from(".") { include 'LICENSE', 'NOTICE' }
//repackaged license
from("lib/repackaged") { include '*.txt' }
}
def repackagedClasses = copySpec {
from(zipTree("lib/repackaged/cglib-and-asm-1.0.jar")) {
exclude 'META-INF/MANIFEST.MF'
allprojects { proj ->
repositories {
jcenter()
}
plugins.withId('java') {
proj.apply plugin: 'net.ltgt.errorprone'
proj.dependencies {
errorprone libraries.errorprone
}
}
tasks.withType(JavaCompile) {
//I don't believe those warnings add value given modern IDEs
options.warnings = false
options.encoding = 'UTF-8'
}
apply plugin: 'checkstyle'
checkstyle {
configFile = rootProject.file('config/checkstyle/checkstyle.xml')
}
}
jar {
baseName = 'mockito-core'
from(sourceSets.main.allSource)
with repackagedClasses
with licenseFiles
}
task sourcesJar(type: Jar) {
baseName = 'mockito-core'
from(sourceSets.main.allSource)
classifier = "sources"
from(zipTree("lib/sources/cglib-and-asm-1.0-sources.jar"))
with licenseFiles
}
apply from: 'gradle/javadoc.gradle'
task javadocJar(type: Jar) {
baseName = 'mockito-core'
classifier = "javadoc"
with licenseFiles
from mockitoJavadoc
configurations {
testUtil //TODO move to separate project
}
//TODO SF mockito-all jar should automatically appear as downloadable in bintray and in Mockito 2.0, replaced with zip distro
task allJar(type: Jar) {
baseName = 'mockito-all'
with repackagedClasses
with licenseFiles
//source files
from(sourceSets.main.allSource)
dependencies {
compile libraries.bytebuddy, libraries.bytebuddyagent
//classes
from(sourceSets.main.output)
compileOnly libraries.junit4, libraries.hamcrest
compile libraries.objenesis
//3rd party library classes
from(zipTree("lib/run/objenesis-2.1.jar")) { exclude "META-INF/maven/**" }
from(zipTree("lib/run/com.springsource.org.hamcrest.core-1.1.0.jar")) { exclude "LICENSE.txt" }
testCompile libraries.asm
//3rd party license files
from("lib/run") { exclude '**/*.jar' }
}
testCompile libraries.assertj
def antCommand = "ant"
//putting 'provided' dependencies on test compile and runtime classpath
testCompileOnly configurations.compileOnly
testRuntime configurations.compileOnly
if (System.getProperty("os.name").startsWith("Windows")) {
antCommand += ".bat"
testUtil sourceSets.test.output
}
configure([jar, allJar]) { task ->
task.rootSpec.exclude "MANIFEST.MF" //hack to avoid problems with bnd
doLast {
project.exec {
commandLine antCommand, '-f', 'build-ant.xml', "osgify.$task.baseName", "-Dversion=$project.version"
}
}
wrapper {
gradleVersion = '4.9'
distributionSha256Sum = 'e66e69dce8173dd2004b39ba93586a184628bc6c28461bc771d6835f7f9b0d28'
}
artifacts {
archives allJar, sourcesJar, javadocJar
//Posting Build scans to https://scans.gradle.com
buildScan {
licenseAgreementUrl = 'https://gradle.com/terms-of-service'
licenseAgree = 'yes'
}
publishing {
publications {
mockitoCore(MavenPublication) {
from components.java
artifactId 'mockito-core'
artifact sourcesJar
artifact javadocJar
}
mockitoAll(MavenPublication) {
artifactId 'mockito-all'
artifact allJar
artifact sourcesJar
artifact javadocJar
//workaround for #1444, delete when Shipkit bug is fixed
subprojects {
afterEvaluate {
def lib = publishing.publications.javaLibrary
if(lib && !lib.artifactId.startsWith("mockito-")) {
lib.artifactId = "mockito-" + lib.artifactId
}
}
}
apply from: 'gradle/release.gradle'
apply from: "gradle/pom.gradle"
task wrapper(type: Wrapper) {
gradleVersion = '2.0'
}
task ciBuild {
//validate the state of the project
dependsOn build, publishToMavenLocal, tasks.idea, tasks.eclipse
}
\ No newline at end of file
//end workaround
This diff is collapsed.
apply plugin: 'idea'
apply plugin: 'groovy'
repositories { jcenter() }
dependencies {
compile gradleApi()
//TODO SF use jcabi to edit issues after the release so that they have the milestone attached
//compile "com.jcabi:jcabi-github:0.17"
compile "com.googlecode.json-simple:json-simple:1.1.1@jar"
testCompile("org.spockframework:spock-core:0.7-groovy-2.0") {
exclude module: "groovy-all"
}
testCompile "cglib:cglib-nodep:2.2.2"
}
if (gradle.parent && gradle.parent.startParameter.taskNames.any { it in ["ideaModule", "idea"] }) {
build.dependsOn ideaModule
}
\ No newline at end of file
package org.mockito.release.comparison;
import groovy.lang.Closure;
import static org.mockito.release.util.ArgumentValidation.notNull;
class PomComparator {
private Closure<String> left;
private Closure<String> right;
PomComparator setPair(Closure<String> left, Closure<String> right) {
notNull(left, "pom content to compare", right, "pom content to compare");
this.left = left;
this.right = right;
return this;
}
boolean areEqual() {
String left = this.left.call();
String right = this.right.call();
notNull(left, "pom content to compare", right, "pom content to compare");
return replaceVersion(left).equals(replaceVersion(right));
}
private String replaceVersion(String pom) {
return pom.replaceFirst("<version>(.*)</version>", "<version>foobar</version>");
}
}
package org.mockito.release.comparison;
import groovy.lang.Closure;
import java.io.File;
/**
* Compares publications
*/
public interface PublicationsComparator {
/**
* Sets files for comparison
*/
void compareBinaries(Closure<File> left, Closure<File> right);
/**
* Sets poms for comparison
*/
void comparePoms(Closure<String> left, Closure<String> right);
/**
* Gives information if publications are equal
*/
boolean isPublicationsEqual();
}
package org.mockito.release.comparison;
import groovy.lang.Closure;
import org.gradle.api.DefaultTask;
import org.gradle.api.tasks.TaskAction;
import java.io.File;
public class PublicationsComparatorTask extends DefaultTask implements PublicationsComparator {
private ZipComparator zipComparator = new ZipComparator(new ZipCompare());
private PomComparator pomComparator = new PomComparator();
private Boolean publicationsEqual;
public void compareBinaries(Closure<File> left, Closure<File> right) {
zipComparator.setPair(left, right);
}
public void comparePoms(Closure<String> left, Closure<String> right) {
pomComparator.setPair(left, right);
}
public boolean isPublicationsEqual() {
assert publicationsEqual != null : "Comparison task was not executed yet, the 'publicationsEqual' information not available.";
return publicationsEqual;
}
@TaskAction public void comparePublications() {
getLogger().lifecycle("{} - about to compare publications", getPath());
boolean poms = pomComparator.areEqual();
getLogger().lifecycle("{} - pom files equal: {}", getPath(), poms);
ZipComparator.Result result = zipComparator.compareFiles();
getLogger().info("{} - compared binaries: '{}' and '{}'", getPath(), result.getFile1(), result.getFile2());
boolean jars = result.areEqual();
getLogger().lifecycle("{} - source jars equal: {}", getPath(), jars);
this.publicationsEqual = jars && poms;
}
}
\ No newline at end of file
package org.mockito.release.comparison;
import groovy.lang.Closure;
import java.io.File;
import static org.mockito.release.util.ArgumentValidation.notNull;
class ZipComparator {
private Closure<File> file1;
private Closure<File> file2;
private final ZipCompare zipCompare;
ZipComparator(ZipCompare zipCompare) {
this.zipCompare = zipCompare;
}
ZipComparator setPair(Closure<File> file1, Closure<File> file2) {
notNull(file1, "zip/jar file to compare", file2, "zip/jar file to compare");
this.file1 = file1;
this.file2 = file2;
return this;
}
Result compareFiles() {
final File file1 = this.file1.call();
final File file2 = this.file2.call();
notNull(file1, "zip/jar file to compare", file2, "zip/jar file to compare");
final boolean equals = zipCompare.compareZips(file1.getAbsolutePath(), file2.getAbsolutePath());
return new Result() {
public boolean areEqual() { return equals; }
public File getFile1() { return file1; }
public File getFile2() { return file2; }
};
}
static interface Result {
boolean areEqual();
File getFile1();
File getFile2();
}
}
package org.mockito.release.comparison;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import static java.lang.String.format;
/**
* Borrowed from the web so it does not look great.
* I've removed System.out.println, fixed exception handling and added coverage.
* For now it might be good enough.
*/
class ZipCompare {
private final static Logger LOG = LoggerFactory.getLogger(ZipCompare.class);
boolean compareZips(String filePath1, String filePath2) {
ZipFile file1;
try {
file1 = new ZipFile(filePath1);
} catch (IOException e) {
throw new ZipCompareException("Could not open zip file " + filePath1, e);
}
ZipFile file2;
try {
file2 = new ZipFile(filePath2);
} catch (IOException e) {
throw new ZipCompareException("Could not open zip file " + filePath1, e);
}
LOG.info("Comparing " + filePath1 + " with " + filePath2);
Set set1 = new LinkedHashSet();
for (Enumeration e = file1.entries(); e.hasMoreElements(); )
set1.add(((ZipEntry) e.nextElement()).getName());
Set set2 = new LinkedHashSet();
for (Enumeration e = file2.entries(); e.hasMoreElements(); )
set2.add(((ZipEntry) e.nextElement()).getName());
int errcount = 0;
int filecount = 0;
for (Iterator i = set1.iterator(); i.hasNext(); ) {
String name = (String) i.next();
if (!set2.contains(name)) {
LOG.info(name + " not found in " + filePath2);
errcount += 1;
continue;
}
try {
set2.remove(name);
if (!streamsEqual(file1.getInputStream(file1.getEntry(name)), file2.getInputStream(file2
.getEntry(name)))) {
LOG.info(name + " does not match");
errcount += 1;
continue;
}
} catch (Exception e) {
throw new ZipCompareException(format("Unable to compare zip entry '%s' found in '%s' with '%s'", name, filePath1, filePath2), e);
}
filecount += 1;
}
for (Iterator i = set2.iterator(); i.hasNext(); ) {
String name = (String) i.next();
LOG.info(name + " not found in " + filePath1);
errcount += 1;
}
LOG.info(filecount + " entries matched");
if (errcount > 0) {
LOG.info(errcount + " entries did not match");
return false;
}
return true;
}
static boolean streamsEqual(InputStream stream1, InputStream stream2) throws IOException {
byte[] buf1 = new byte[4096];
byte[] buf2 = new byte[4096];
boolean done1 = false;
boolean done2 = false;
try {
while (!done1) {
int off1 = 0;
int off2 = 0;
while (off1 < buf1.length) {
int count = stream1.read(buf1, off1, buf1.length - off1);
if (count < 0) {
done1 = true;
break;
}
off1 += count;
}
while (off2 < buf2.length) {
int count = stream2.read(buf2, off2, buf2.length - off2);
if (count < 0) {
done2 = true;
break;
}
off2 += count;
}
if (off1 != off2 || done1 != done2)
return false;
for (int i = 0; i < off1; i++) {
if (buf1[i] != buf2[i])
return false;
}
}
return true;
} finally {
stream1.close();
stream2.close();
}
}
static class ZipCompareException extends RuntimeException {
public ZipCompareException(String message, Throwable cause) {
super(message, cause);
}
}
}
\ No newline at end of file
package org.mockito.release.exec;
import org.mockito.release.notes.util.ReleaseNotesException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.util.Arrays;
class DefaultProcessRunner implements ProcessRunner {
private static Logger LOG = LoggerFactory.getLogger(DefaultProcessRunner.class);
private final File workDir;
DefaultProcessRunner(File workDir) {
this.workDir = workDir;
}
public String run(String... commandLine) {
LOG.info("Executing command: {}", (Object) commandLine);
try {
Process process = new ProcessBuilder(commandLine).directory(workDir).redirectErrorStream(true).start();
return readFully(new BufferedReader(new InputStreamReader(process.getInputStream())));
} catch (Exception e) {
throw new ReleaseNotesException("Problems executing command: " + Arrays.toString(commandLine), e);
}
}
private static String readFully(BufferedReader reader) throws IOException {
try {
StringBuilder sb = new StringBuilder();
String line;
while((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
return sb.toString();
} finally {
reader.close();
}
}
}
package org.mockito.release.exec;
import java.io.File;
/**
* Process execution services
*/
public class Exec {
/**
* Provides process runner for given working dir
*/
public static ProcessRunner getProcessRunner(File workDir) {
return new DefaultProcessRunner(workDir);
}
}
package org.mockito.release.exec;
/**
* Provides ways to execute external processes
*/
public interface ProcessRunner {
/**
* Executes given command line and returns the output.
*
* @param commandLine to execute
* @return combined error and standard output.
*/
String run(String ... commandLine);
}