instance_id
stringlengths 17
39
| repo
stringclasses 8
values | issue_id
stringlengths 14
34
| pr_id
stringlengths 14
34
| linking_methods
sequencelengths 1
3
| base_commit
stringlengths 40
40
| merge_commit
stringlengths 0
40
⌀ | hints_text
sequencelengths 0
106
| resolved_comments
sequencelengths 0
119
| created_at
unknown | labeled_as
sequencelengths 0
7
| problem_title
stringlengths 7
174
| problem_statement
stringlengths 0
55.4k
| gold_files
sequencelengths 0
10
| gold_files_postpatch
sequencelengths 1
10
| test_files
sequencelengths 0
60
| gold_patch
stringlengths 220
5.83M
| test_patch
stringlengths 386
194k
⌀ | split_random
stringclasses 3
values | split_time
stringclasses 3
values | issue_start_time
timestamp[ns] | issue_created_at
unknown | issue_by_user
stringlengths 3
21
| split_repo
stringclasses 3
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
iluwatar/java-design-patterns/2333_2461 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/2333 | iluwatar/java-design-patterns/2461 | [
"keyword_pr_to_issue"
] | 08682962b5f941caebbae863ab309a69779c0dc7 | 0eb976394bab5d58acb2d246160adad4d072f314 | [
"Hello ! I am new in opensource and I am also familiar with java I want to use this skill in real-world project. can anyone help me too start this project or how can I solve this .\r\n ",
"There is just a broken link in the mentioned document @Pawank06 I suppose it should be an easy fix.",
"> Hello ! I am new in opensource and I am also familiar with java I want to use this skill in real-world project. can anyone help me too start this project or how can I solve this .\r\n\r\nYou can fix it by updating the path from\r\n`https://github.com/iluwatar/java-design-patterns/workflows/Java%20CI%20with%20Maven/badge.svg`\r\nto\r\n`https://github.com/iluwatar/java-design-patterns/workflows/Java%20CI/badge.svg`"
] | [] | "2023-01-24T15:02:13Z" | [
"type: bug",
"info: help wanted",
"info: good first issue",
"epic: documentation"
] | Broken linkage on Chinese localization document | Broken linkage [Java CI with Maven](https://github.com/iluwatar/java-design-patterns/workflows/Java%20CI%20with%20Maven/badge.svg) on the following Chinese localization README file.
https://github.com/iluwatar/java-design-patterns/blob/master/localization/zh/README.md
| [
"localization/zh/README.md"
] | [
"localization/zh/README.md"
] | [] | diff --git a/localization/zh/README.md b/localization/zh/README.md
index dcf8571b5764..6b810cd48e9a 100644
--- a/localization/zh/README.md
+++ b/localization/zh/README.md
@@ -4,7 +4,7 @@
# 设计模式Java版
-![Java CI with Maven](https://github.com/iluwatar/java-design-patterns/workflows/Java%20CI%20with%20Maven/badge.svg) [](https://raw.githubusercontent.com/iluwatar/java-design-patterns/master/LICENSE.md)![License MIT](https://img.shields.io/badge/license-MIT-blue.svg) [](https://gitter.im/iluwatar/java-design-patterns?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)![Join the chat at https://gitter.im/iluwatar/java-design-patterns](https://badges.gitter.im/Join%20Chat.svg) [](https://sonarcloud.io/dashboard?id=iluwatar_java-design-patterns)![Sonarcloud Status](https://sonarcloud.io/api/project_badges/measure?project=iluwatar_java-design-patterns&metric=alert_status)
+![Java CI with Maven](https://github.com/iluwatar/java-design-patterns/workflows/Java%20CI/badge.svg) [](https://raw.githubusercontent.com/iluwatar/java-design-patterns/master/LICENSE.md)![License MIT](https://img.shields.io/badge/license-MIT-blue.svg) [](https://gitter.im/iluwatar/java-design-patterns?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)![Join the chat at https://gitter.im/iluwatar/java-design-patterns](https://badges.gitter.im/Join%20Chat.svg) [](https://sonarcloud.io/dashboard?id=iluwatar_java-design-patterns)![Sonarcloud Status](https://sonarcloud.io/api/project_badges/measure?project=iluwatar_java-design-patterns&metric=alert_status)
# 介绍
| null | test | test | 2023-01-21T19:21:06 | "2022-11-13T17:00:25Z" | limingho456 | train |
iluwatar/java-design-patterns/2459_2467 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/2459 | iluwatar/java-design-patterns/2467 | [
"keyword_pr_to_issue"
] | c741814b367f004787ef2f87665cc00b5f07b35e | 4e8cdc7c960ce991fce94cfb0143466e9526a6a6 | [
"It's called **Double-Checked Locking**. [REFER](https://en.wikipedia.org/wiki/Double-checked_locking#Usage_in_Java) \r\nHope your doubt is resolved after reading the above article!\r\n",
"Hi @bharathkalyans thank you for reference.\r\nMy doubt is actually if we already have a `volatile` instance, any thread will see the latest updated value of that instance. Why do we need to wrap the first null check in a synchronized block(via the method signature).",
"Please [REFER](http://jeremymanson.blogspot.com/2008/11/what-volatile-means-in-java.html) to this article's second section for a better understanding of why volatile must be used!!",
"I understand why `volatile` is used here. What I didn't understand is why we need synchronized in this method signature? `public static synchronized ThreadSafeLazyLoadedIvoryTower getInstance()`, given that `instance` is already `volatile`, why do we need to take a lock here?",
"You have a good point there @hmittal657 The [implementation](https://github.com/iluwatar/java-design-patterns/blob/master/singleton/src/main/java/com/iluwatar/singleton/ThreadSafeLazyLoadedIvoryTower.java) does look a bit confusing since it mixes `synchronized` method with some elements from the double-checked locking. I think we should reduce it to something like this to improve clarity:\r\n\r\n```\r\npublic static synchronized ThreadSafeLazyLoadedIvoryTower getInstance() {\r\n if (instance == null) {\r\n instance = new ThreadSafeLazyLoadedIvoryTower();\r\n }\r\n return instance;\r\n}\r\n```\r\n\r\nNote that we are trying to demonstrate different ways to implement the singleton. At the moment we have\r\n\r\n- IvoryTower - eagerly initialized thread safe singleton\r\n- ThreadSafeLazyLoadedIvoryTower - basic lazy loaded singleton using `synchronized`\r\n- ThreadSafeDoubleCheckedLocking - lazy loaded singleton using double-checked locking\r\n- InitializingOnDemandHolderIdiom - lazy loaded singleton using inner class\r\n- EnumIvoryTower - lazy loaded singleton using enum\r\n\r\nI'm also not happy with the current level of documentation we have. There is an [open issue](https://github.com/iluwatar/java-design-patterns/issues/187) to improve it.\r\n",
"@iluwatar Do you want me to work on this?\r\n```\r\npublic static synchronized ThreadSafeLazyLoadedIvoryTower getInstance() {\r\n if (instance == null) {\r\n instance = new ThreadSafeLazyLoadedIvoryTower();\r\n }\r\n return instance;\r\n}\r\n```",
"I think it should be enough to remove `synchronized` from the method signature. We still would have double check locking and avoid expensive locking in the method calls",
"@hmittal657 that case is already demonstrated in ThreadSafeDoubleCheckedLocking. We don't want to duplicate it.\r\n\r\n@bharathkalyans I'll assign you for this"
] | [] | "2023-02-02T07:12:00Z" | [
"type: bug",
"type: support",
"epic: pattern"
] | Why are we using synchronized twice in com.iluwatar.singleton.ThreadSafeLazyLoadedIvoryTower? | `/**
* The instance doesn't get created until the method is called for the first time.
*/
public static synchronized ThreadSafeLazyLoadedIvoryTower getInstance() {
if (instance == null) {
synchronized (ThreadSafeLazyLoadedIvoryTower.class) {
if (instance == null) {
instance = new ThreadSafeLazyLoadedIvoryTower();
}
}
}
return instance;
}`
Shouldn't we remove synchronized from method signature? I didn't find any explaination for this. Usually for lazy initialization we have synchronized only inside the method right?
What pros/cons are there for using synchronized in method signature?
[Code reference](https://github.com/iluwatar/java-design-patterns/blob/master/singleton/src/main/java/com/iluwatar/singleton/ThreadSafeLazyLoadedIvoryTower.java#L46) | [
"singleton/src/main/java/com/iluwatar/singleton/ThreadSafeLazyLoadedIvoryTower.java"
] | [
"singleton/src/main/java/com/iluwatar/singleton/ThreadSafeLazyLoadedIvoryTower.java"
] | [] | diff --git a/singleton/src/main/java/com/iluwatar/singleton/ThreadSafeLazyLoadedIvoryTower.java b/singleton/src/main/java/com/iluwatar/singleton/ThreadSafeLazyLoadedIvoryTower.java
index 58d6e53b9729..fcafba3611c5 100644
--- a/singleton/src/main/java/com/iluwatar/singleton/ThreadSafeLazyLoadedIvoryTower.java
+++ b/singleton/src/main/java/com/iluwatar/singleton/ThreadSafeLazyLoadedIvoryTower.java
@@ -44,13 +44,9 @@ private ThreadSafeLazyLoadedIvoryTower() {
* The instance doesn't get created until the method is called for the first time.
*/
public static synchronized ThreadSafeLazyLoadedIvoryTower getInstance() {
- if (instance == null) {
- synchronized (ThreadSafeLazyLoadedIvoryTower.class) {
- if (instance == null) {
+ if (instance == null) {
instance = new ThreadSafeLazyLoadedIvoryTower();
- }
}
- }
return instance;
}
}
| null | train | test | 2023-02-04T18:37:34 | "2023-01-23T12:38:34Z" | hmittal657 | train |
iluwatar/java-design-patterns/1965_2470 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/1965 | iluwatar/java-design-patterns/2470 | [
"keyword_pr_to_issue"
] | c741814b367f004787ef2f87665cc00b5f07b35e | 18b1d5195f5ced99a4dc9cb12157aac97b6e2ffc | [
"Can you give more specific info about this bug or sth. ?",
"![image](https://user-images.githubusercontent.com/48951804/190575773-3b447290-fb39-4acf-a0ed-99145da97675.png)\r\n",
"This issue is free for taking again.",
"Can you specify more about this.!",
"@nairpranav331 It is a Chinese translation error.",
"Subtask of #2289 ",
"I can fix this! Can I take it?",
"@iluwatar Can you check this please? \r\n#2470 "
] | [] | "2023-02-07T17:40:04Z" | [
"type: bug",
"epic: pattern",
"epic: web site",
"info: good first issue"
] | Translation error | ![image](https://user-images.githubusercontent.com/39300225/154443661-c12f821f-5942-4903-b158-8c5450711ab8.png)
| [
"localization/zh/abstract-factory/README.md"
] | [
"localization/zh/abstract-factory/README.md"
] | [] | diff --git a/localization/zh/abstract-factory/README.md b/localization/zh/abstract-factory/README.md
index 5241e31c7ba5..092d87624132 100644
--- a/localization/zh/abstract-factory/README.md
+++ b/localization/zh/abstract-factory/README.md
@@ -18,7 +18,7 @@ tag:
真实世界例子
-> 要创建一个王国,我们需要具有共同主题的对象。 精灵王国需要精灵王,精灵城堡和精灵军队,而兽人王国需要兽王,精灵城堡和兽人军队。 王国中的对象之间存在依赖性。
+> 要创建一个王国,我们需要具有共同主题的对象。精灵王国需要精灵国王、精灵城堡和精灵军队,而兽人王国需要兽人国王、兽人城堡和兽人军队。王国中的对象之间存在依赖关系。
通俗的说
| null | train | test | 2023-02-04T18:37:34 | "2022-02-17T09:14:57Z" | liuyangyudaxia | train |
iluwatar/java-design-patterns/2472_2474 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/2472 | iluwatar/java-design-patterns/2474 | [
"keyword_pr_to_issue",
"timestamp(timedelta=6.0, similarity=0.9391483888332116)"
] | 1fa80eb74cd9d69aae394c4e730db82bb1f2d904 | 188f35aafc99c40523e3f154f1fe04a558a679c0 | [
"Part of #2277 "
] | [] | "2023-02-16T19:48:46Z" | [
"type: feature",
"epic: translation"
] | Translate the api-gateway readme to Spanish. | Hello, I will continue with the spanish translations for readme files [here](https://github.com/iluwatar/java-design-patterns/issues/2277), next one is api-gateway, I will place it under localization.es.api-gateway | [] | [
"localization/es/api-gateway/README.md"
] | [] | diff --git a/localization/es/api-gateway/README.md b/localization/es/api-gateway/README.md
new file mode 100644
index 000000000000..b2336313fded
--- /dev/null
+++ b/localization/es/api-gateway/README.md
@@ -0,0 +1,168 @@
+---
+title: API Gateway
+category: Architectural
+language: es
+tag:
+ - Cloud distributed
+ - Decoupling
+ - Microservices
+---
+
+## Motivo
+
+Agregar llamadas a los microservicios en un mismo lugar, la puerta de enlace API (API Gateway). El usuario
+hace un llamada simple al API Gateway, y la API Gateway hace la llamada a cada microservicio relevante.
+
+## Explicaición
+
+Con el patrón de microservicios, el cliente puede necesitar datos de múltiples microservicios. Si el
+cliente llamara a cada microservicio de forma directe, podría ocasionar tiempos de carga largos, ya que
+el cliente tendría que hacer una solicitud de red para cada microservicio llamado. Además, tener la
+la llamada del cliente a cada microservicio vincula directamente al cliente con ese microservicio - si la
+implementacion interna del cambio de microservicios (por ejemplo, si dos microservicios se combinan en
+algún momento en el futuro) o si la ubicación (host y puerto) de un microservicio cambia, entonces cada
+cliente que hace uso de esos microservicios debe ser actualizado.
+
+La intención del patrón API Gateway es aliviar algunos de estos problemas. En el patrón API Gateway,
+se coloca una entidad adicional (la API Gateway) entre el cliente y los microservicios.
+El trabajo de API Gateway es agregar las llamadas a los microservicios. En lugar de que el cliente
+llame a cada microservicio individualmente, el cliente llama al API Gateway una sola vez. la API
+Gateway luego llama a cada uno de los microservicios que necesita el cliente.
+
+Ejemplo real
+
+> Estamos implementando un sistema de microservicios y API Gateway para un sitio e-commerce. En este
+> sistema API Gateway realiza llamadas a los microservicios Image y Price. (Imagen y Precio)
+
+En otras palabras
+
+> Para un sistema implementado utilizando una arquitectura de microservicios, API Gateway es el único
+> punto de entrada que agrega las llamadas a los microservicios individuales.
+
+Wikipedia dice
+
+> API Gateway es un servidor que actúa como un front-end de API, recibe solicitudes de API, aplica la
+> limitación y políticas de seguridad, pasa las solicitudes al servicio back-end y luego devuelve la
+> respuesta al solicitante. Una puerta de enlace a menudo incluye un motor de transformación para
+> orquestar y modificar las solicitudes y respuestas sobre la marcha. Una puerta de enlace también
+> puede proporcionar funciones como recopilar análisis de datos y almacenamiento en caché. La puerta
+> de enlace puede proporcionar funcionalidad para soportar autenticación, autorización, seguridad,
+> auditoría y cumplimiento normativo.
+
+**Código de ejemplo**
+
+Esta implementación muestra cómo podría verse el patrón API Gateway para un sitio de e-commerce. El
+`ApiGateway` hace llamadas a los microservicios Image y Price usando `ImageClientImpl` y`PriceClientImpl`
+respectivamente. Los clientes que ven el sitio en un dispositivo de escritorio pueden ver la información
+de precio y una imagen de un producto, entonces `ApiGateway` llama a los microservicios y
+agrega los datos en el modelo `DesktopProduct`. Sin embargo, los usuarios de dispositivos móviles solo
+ven información de precios, no ven una imagen del producto. Para usuarios móviles, `ApiGateway` solo
+recupera el precio información, que utiliza para completar el `MobileProduct`.
+
+Aquí está la implementación del microservicio de imagen (Image).
+
+```java
+public interface ImageClient {
+ String getImagePath();
+}
+
+public class ImageClientImpl implements ImageClient {
+ @Override
+ public String getImagePath() {
+ var httpClient = HttpClient.newHttpClient();
+ var httpGet = HttpRequest.newBuilder()
+ .GET()
+ .uri(URI.create("http://localhost:50005/image-path"))
+ .build();
+
+ try {
+ var httpResponse = httpClient.send(httpGet, BodyHandlers.ofString());
+ return httpResponse.body();
+ } catch (IOException | InterruptedException e) {
+ e.printStackTrace();
+ }
+
+ return null;
+ }
+}
+```
+
+Aquí está la implementación del microservicio de precio (Price).
+
+```java
+public interface PriceClient {
+ String getPrice();
+}
+
+public class PriceClientImpl implements PriceClient {
+
+ @Override
+ public String getPrice() {
+ var httpClient = HttpClient.newHttpClient();
+ var httpGet = HttpRequest.newBuilder()
+ .GET()
+ .uri(URI.create("http://localhost:50006/price"))
+ .build();
+
+ try {
+ var httpResponse = httpClient.send(httpGet, BodyHandlers.ofString());
+ return httpResponse.body();
+ } catch (IOException | InterruptedException e) {
+ e.printStackTrace();
+ }
+
+ return null;
+ }
+}
+```
+
+Aquí podemos ver cómo API Gateway asigna las solicitudes a los microservicios.
+
+```java
+public class ApiGateway {
+
+ @Resource
+ private ImageClient imageClient;
+
+ @Resource
+ private PriceClient priceClient;
+
+ @RequestMapping(path = "/desktop", method = RequestMethod.GET)
+ public DesktopProduct getProductDesktop() {
+ var desktopProduct = new DesktopProduct();
+ desktopProduct.setImagePath(imageClient.getImagePath());
+ desktopProduct.setPrice(priceClient.getPrice());
+ return desktopProduct;
+ }
+
+ @RequestMapping(path = "/mobile", method = RequestMethod.GET)
+ public MobileProduct getProductMobile() {
+ var mobileProduct = new MobileProduct();
+ mobileProduct.setPrice(priceClient.getPrice());
+ return mobileProduct;
+ }
+}
+```
+
+## Diagrama de clase
+
+![alt text](/api-gateway/etc/api-gateway.png "API Gateway")
+
+## Aplicaciones
+
+Usa el patrón de API Gateway cuando
+
+* Estés usando una arquitectura de microservicios y necesites un único punto de agregación para las llamadas de microservicios.
+
+## Tutoriales
+
+* [Exploring the New Spring Cloud Gateway](https://www.baeldung.com/spring-cloud-gateway)
+* [Spring Cloud - Gateway](https://www.tutorialspoint.com/spring_cloud/spring_cloud_gateway.htm)
+* [Getting Started With Spring Cloud Gateway](https://dzone.com/articles/getting-started-with-spring-cloud-gateway)
+
+## Créditos
+
+* [microservices.io - API Gateway](http://microservices.io/patterns/apigateway.html)
+* [NGINX - Building Microservices: Using an API Gateway](https://www.nginx.com/blog/building-microservices-using-an-api-gateway/)
+* [Microservices Patterns: With examples in Java](https://www.amazon.com/gp/product/1617294543/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=1617294543&linkId=ac7b6a57f866ac006a309d9086e8cfbd)
+* [Building Microservices: Designing Fine-Grained Systems](https://www.amazon.com/gp/product/1491950358/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=1491950358&linkId=4c95ca9831e05e3f0dadb08841d77bf1)
| null | train | test | 2023-02-11T18:09:51 | "2023-02-14T04:03:49Z" | TheClerici | train |
iluwatar/java-design-patterns/2476_2477 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/2476 | iluwatar/java-design-patterns/2477 | [
"keyword_pr_to_issue"
] | c34ad292e3de91e2aa3ede878a9d929e3a6b7477 | 207cf60bc6b7e4b2e912c51ea564e4eaf3f851cd | [] | [] | "2023-02-19T07:09:54Z" | [
"type: bug",
"info: help wanted",
"info: good first issue",
"epic: translation"
] | Typo in README in Russian | ускорить процесс разработк`у` -> ускорить процесс разработк`и` | [
"localization/ru/README.md"
] | [
"localization/ru/README.md"
] | [] | diff --git a/localization/ru/README.md b/localization/ru/README.md
index a52020200830..89e4ddffc317 100644
--- a/localization/ru/README.md
+++ b/localization/ru/README.md
@@ -17,7 +17,7 @@
Шаблоны проектирования - лучший метод для решения проблем, возникающих
во время разработки приложения или системы.
-Шаблоны проектирования могут ускорить процесс разработку путем предоставления
+Шаблоны проектирования могут ускорить процесс разработки путем предоставления
проверенных моделей/парадигм.
Использование шаблонов повторно поможет избежать частых проблем, из-за которых
| null | train | test | 2023-02-18T19:56:22 | "2023-02-19T07:08:46Z" | ramilS | train |
iluwatar/java-design-patterns/2479_2480 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/2479 | iluwatar/java-design-patterns/2480 | [
"keyword_pr_to_issue"
] | 91321c83778adfa40f449ad18008c33c5e6237ca | 84f7ab8006f4ba0f193e02362297ff8ba2701542 | [
"Subtask of https://github.com/iluwatar/java-design-patterns/issues/2277"
] | [] | "2023-02-24T22:51:32Z" | [
"type: feature",
"epic: translation"
] | Translate arrange-act-assert to spanish (Task of issue #2277) | Translation of [arrange-act-assert/README.md](https://github.com/iluwatar/java-design-patterns/blob/master/arrange-act-assert/README.md) to [java-design-patterns/localization/es/arrange-act-assert/](https://github.com/iluwatar/java-design-patterns/tree/master/localization/es/) folder
Task of issue #2277 | [] | [
"localization/es/arrange-act-assert/README.md",
"localization/es/async-method-invocation/README.md"
] | [] | diff --git a/localization/es/arrange-act-assert/README.md b/localization/es/arrange-act-assert/README.md
new file mode 100644
index 000000000000..d5411e63b7ad
--- /dev/null
+++ b/localization/es/arrange-act-assert/README.md
@@ -0,0 +1,140 @@
+---
+title: Arrange/Act/Assert
+category: Idiom
+language: es
+tag:
+ - Testing
+---
+
+## También conocido como
+
+Dado/Cuando/Entonces
+
+## Intención
+
+Arrange/Act/Assert (AAA) es un patrón para organizar UnitTests.
+Divide las UnitTests en tres pasos claros y diferenciados:
+
+1. Arrange(Organizar): Realiza la configuración y la inicialización necesarias para el test.
+2. Act(Actuar): Toma las medidas necesarias para el test.
+3. Assert(Afirmar): Verifica los resultados del test.
+
+## Explicacación
+
+Este patrón tiene varios beneficios significativos. Crea una clara separación entre la configuración, operaciones y resultados de un test. Esta estructura hace que el código sea más fácil de leer y comprender. Si
+colocas los pasos en orden y formateas su código para separarlos, puedes escanear un test y
+comprender rápidamente lo que hace.
+
+También impone un cierto grado de disciplina cuando escribes tus UnitTests. Tienes que visualizar
+claramente los tres pasos que tu test realizará. Esto hace que los tests sean más intuitivos de escribir a la vez que tienes presente un esquema.
+
+Ejemplo cotidiano
+
+> Necesitamos escribir un conjunto de UnitTests completo y claro para una clase.
+
+En otras palabras
+
+> Arrange/Act/Assert es un patrón de testeo que organiza las pruebas en tres pasos claros para facilitar su
+> mantenimiento.
+
+WikiWikiWeb dice
+
+> Arrange/Act/Assert es un patrón para organizar y dar formato al código en los métodos UnitTest.
+
+**Código de ejemplo**
+
+Veamos primero nuestra clase `Cash` para que sea testeada.
+
+```java
+public class Cash {
+
+ private int amount;
+
+ Cash(int amount) {
+ this.amount = amount;
+ }
+
+ void plus(int addend) {
+ amount += addend;
+ }
+
+ boolean minus(int subtrahend) {
+ if (amount >= subtrahend) {
+ amount -= subtrahend;
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ int count() {
+ return amount;
+ }
+}
+```
+
+Luego escribimos nuestras UnitTests en función del patrón Arrange/Act/Assert. Note claramente la separación de los pasos para cada UnitTest.
+
+```java
+class CashAAATest {
+
+ @Test
+ void testPlus() {
+ //Arrange
+ var cash = new Cash(3);
+ //Act
+ cash.plus(4);
+ //Assert
+ assertEquals(7, cash.count());
+ }
+
+ @Test
+ void testMinus() {
+ //Arrange
+ var cash = new Cash(8);
+ //Act
+ var result = cash.minus(5);
+ //Assert
+ assertTrue(result);
+ assertEquals(3, cash.count());
+ }
+
+ @Test
+ void testInsufficientMinus() {
+ //Arrange
+ var cash = new Cash(1);
+ //Act
+ var result = cash.minus(6);
+ //Assert
+ assertFalse(result);
+ assertEquals(1, cash.count());
+ }
+
+ @Test
+ void testUpdate() {
+ //Arrange
+ var cash = new Cash(5);
+ //Act
+ cash.plus(6);
+ var result = cash.minus(3);
+ //Assert
+ assertTrue(result);
+ assertEquals(8, cash.count());
+ }
+}
+```
+
+## Aplicabilidad
+
+Utilice el patrón Arrange/Act/Asert cuando
+
+* Necesites estructurar tus UnitTests para que sean más fáciles de leer, mantener y mejorar.
+
+## Créditos
+
+* [Arrange, Act, Assert: ¿Qué son las pruebas AAA?](https://blog.ncrunch.net/post/arrange-act-assert-aaa-testing.aspx)
+* [Bill Wake: 3A – Arrange, Act, Assert](https://xp123.com/articles/3a-arrange-act-assert/)
+* [Martin Fowler: DadoCuandoEntonces](https://martinfowler.com/bliki/GivenWhenThen.html)
+* [Patrones de prueba xUnit: Refactorizando Código de prueba](https://www.amazon.com/gp/product/0131495054/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=0131495054&linkId=99701e8f4af2f63d0bcf50)
+* [Principios, prácticas y patrones UnitTesting](https://www.amazon.com/gp/product/1617296279/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=1617296279&linkId=74c75cfae3a5a)accae3a5a)
+* [Desarrollo basado en pruebas: Ejemplo](https://www.amazon.com/gp/product/0321146530/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=0321146530&linkId=5c63a93d8c1175b47caef50875)
diff --git a/localization/es/async-method-invocation/README.md b/localization/es/async-method-invocation/README.md
new file mode 100644
index 000000000000..756f686767f6
--- /dev/null
+++ b/localization/es/async-method-invocation/README.md
@@ -0,0 +1,168 @@
+---
+title: Async Method Invocation
+category: Concurrency
+language: es
+tag:
+ - Reactive
+---
+
+## Propósito
+
+Asynchronous method invocation (invocación de método asincrónico) es un patrón con el que el hilo o subproceso de llamada
+no se bloquea mientras espera resultados. El patrón proporciona pocesamiento en paralelo de múltiples tareas independientes y recupera los resultados a través de
+devoluciones de llamada (callbacks) o esperando hasta que termine el procedimiento.
+
+## Explicación
+
+Ejemplo cotidiano
+
+> Lanzar cohetes espaciales es un negocio apasionante. El comandante de la misión da la orden de lanzamiento y
+> después de un tiempo indeterminado, el cohete se lanza con éxito o falla miserablemente.
+
+En otras palabras
+
+> La invocación del método asíncrono inicia el procedimiento y vuelve inmediatamente antes de que la tarea termine
+> Los resultados del procedimiento se devuelven a la llamada posteriormente (callback).
+
+Según Wikipedia
+
+> En la programación multiproceso, la invocación de método asíncrono (AMI), también conocida como
+> llamadas de método asíncrono o el patrón asíncrono es un patrón de diseño en el que el lugar de la llamada
+> no se bloquea mientras espera que termine el código llamado. En cambio, el hilo de llamada es
+> notificado cuando llega la respuesta. Sondear para obtener una respuesta es una opción no deseada.
+
+**Ejemplo programático**
+
+En este ejemplo, estamos lanzando cohetes espaciales y desplegando vehículos lunares.
+
+La aplicación demuestra lo que hace el patrón de invocación del método asíncrono. Las partes clave del patrón son
+`AsyncResult` que es un contenedor intermedio para un valor evaluado de forma asíncrona,
+`AsyncCallback` que se puede proporcionar para que se ejecute al finalizar la tarea y `AsyncExecutor` que
+gestiona la ejecución de las tareas asíncronas.
+
+```java
+public interface AsyncResult<T> {
+ boolean isCompleted();
+ T getValue() throws ExecutionException;
+ void await() throws InterruptedException;
+}
+```
+
+```java
+public interface AsyncCallback<T> {
+ void onComplete(T value, Optional<Exception> ex);
+}
+```
+
+```java
+public interface AsyncExecutor {
+ <T> AsyncResult<T> startProcess(Callable<T> task);
+ <T> AsyncResult<T> startProcess(Callable<T> task, AsyncCallback<T> callback);
+ <T> T endProcess(AsyncResult<T> asyncResult) throws ExecutionException, InterruptedException;
+}
+```
+
+`ThreadAsyncExecutor` es una implementación de `AsyncExecutor`. Se destacan algunas de sus partes clave a continuación.
+
+```java
+public class ThreadAsyncExecutor implements AsyncExecutor {
+
+ @Override
+ public <T> AsyncResult<T> startProcess(Callable<T> task) {
+ return startProcess(task, null);
+ }
+
+ @Override
+ public <T> AsyncResult<T> startProcess(Callable<T> task, AsyncCallback<T> callback) {
+ var result = new CompletableResult<>(callback);
+ new Thread(
+ () -> {
+ try {
+ result.setValue(task.call());
+ } catch (Exception ex) {
+ result.setException(ex);
+ }
+ },
+ "executor-" + idx.incrementAndGet())
+ .start();
+ return result;
+ }
+
+ @Override
+ public <T> T endProcess(AsyncResult<T> asyncResult)
+ throws ExecutionException, InterruptedException {
+ if (!asyncResult.isCompleted()) {
+ asyncResult.await();
+ }
+ return asyncResult.getValue();
+ }
+}
+```
+
+Ahora está todo preparado para lanzar algunos cohetes y así poder ver cómo funciona todo.
+
+```java
+public static void main(String[] args) throws Exception {
+ // construye un nuevo objeto executor que ejecutará tareas asíncronas
+ var executor = new ThreadAsyncExecutor();
+
+ // inicia algunas tareas asíncronas con diferentes tiempos de procesamiento, las dos últimas con controladores de devolución de llamada
+ final var asyncResult1 = executor.startProcess(lazyval(10, 500));
+ final var asyncResult2 = executor.startProcess(lazyval("test", 300));
+ final var asyncResult3 = executor.startProcess(lazyval(50L, 700));
+ final var asyncResult4 = executor.startProcess(lazyval(20, 400), callback("Desplegando el rover lunar"));
+ final var asyncResult5 =
+ executor.startProcess(lazyval("devolución de llamada callback", 600), callback("Desplegando el rover lunar"));
+
+ // emula el procesamiento en el hilo o subproceso actual mientras las tareas asíncronas se ejecutan en sus propios hilos o subprocesos
+ Subproceso.dormir(350); // Oye, estamos trabajando duro aquí
+ log("El comandante de la misión está bebiendo café");
+
+ // espera a que se completen las tareas
+ final var result1 = executor.endProcess(asyncResult1);
+ final var result2 = executor.endProcess(asyncResult2);
+ final var result3 = executor.endProcess(asyncResult3);
+ asyncResult4.await();
+ asyncResult5.await();
+
+ // registra los resultados de las tareas, las devoluciones de las llamadas se registran inmediatamente cuando se completan
+ log("Cohete espacial <" + resultado1 + "> ha completado su lanzamiento");
+ log("Cohete espacial <" + resultado2 + "> ha completado su lanzamiento");
+ log("Cohete espacial <" + result3 + "> ha completado su lanzamiento");
+}
+```
+
+Aquí está la salida de la consola del programa.
+
+```java
+21:47:08.227 [executor-2] INFO com.iluwatar.async.method.invocation.App - Cohete espacial <prueba> lanzado con éxito
+21:47:08.269 [main] INFO com.iluwatar.async.method.invocation.App - El comandante de la misión está bebiendo café
+21:47:08.318 [executor-4] INFO com.iluwatar.async.method.invocation.App - Cohete espacial <20> lanzado con éxito
+21:47:08.335 [executor-4] INFO com.iluwatar.async.method.invocation.App Desplegando el rover lunar <20>
+21:47:08.414 [executor-1] INFO com.iluwatar.async.method.invocation.App - Cohete espacial <10> lanzado con éxito
+21:47:08.519 [executor-5] INFO com.iluwatar.async.method.invocation.App - Cohete espacial <devolución de llamada callback> lanzado con éxito
+21:47:08.519 [executor-5] INFO com.iluwatar.async.method.invocation.App - Implementando el vehículo lunar <devolución de llamada callback>
+21:47:08.616 [executor-3] INFO com.iluwatar.async.method.invocation.App - Cohete espacial <50> lanzado con éxito
+21:47:08.617 [main] INFO com.iluwatar.async.method.invocation.App - Lanzamiento del cohete espacial <10> completado
+21:47:08.617 [main] INFO com.iluwatar.async.method.invocation.App - Lanzamiento de cohete espacial <prueba> completado
+21:47:08.618 [main] INFO com.iluwatar.async.method.invocation.App - Lanzamiento del cohete espacial <50> completado
+```
+
+# Diagrama de clase
+
+![texto alternativo](./etc/async-method-invocation.png "Invocación de método asíncrono")
+
+## Aplicabilidad
+
+Utiliza el patrón de invocación del método asíncrono cuando
+
+* Tienes múltiples tareas independientes que pueden ejecutarse en paralelo
+* Necesitas mejorar el desempeño de un grupo de tareas secuenciales
+* Tienes una cantidad limitada de capacidad de procesamiento o tareas de ejecución prolongada y la llamada no debe esperar a que las tareas estén listas
+
+## Ejemplos cotidianos
+
+* [FutureTask](http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/FutureTask.html)
+* [CompletableFuture](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html)
+* [ExecutorService](http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html)
+* [Patrón asíncrono basado en tareas](https://msdn.microsoft.com/en-us/library/hh873175.aspx)
\ No newline at end of file
| null | train | test | 2023-02-28T08:33:40 | "2023-02-24T21:10:12Z" | KarmaTashiCat | train |
iluwatar/java-design-patterns/2462_2484 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/2462 | iluwatar/java-design-patterns/2484 | [
"keyword_pr_to_issue"
] | 4bea173e642ce550d84075af0e43efa7f61be359 | b0cc0943f986af20fd7632423d8786fb82ad6dfb | [
"can you assign me this issue?\r\n\r\nI am interest in solve this issue?",
"I'm new to open-sourcing and I have no clue about what I should be doing. Can anyone guide me? I have basic knowledge of java \r\nlet me know in which way I can help you.",
"@jaswanthg76 https://github.com/iluwatar/java-design-patterns/wiki/01.-How-to-contribute",
"Hey I can help in this issue, provide me the information of issue\r\n",
"Hi @vatsasiddhartha, the problem has actually been solved and the fix has been merged"
] | [] | "2023-03-01T15:26:21Z" | [
"type: bug",
"info: help wanted",
"epic: documentation"
] | Wrong generic type for deques in command README | Hi, inside the README.md for the command pattern the Wizard class presents these two instance variables:
```java
private final Deque<Command> undoStack = new LinkedList<>();
private final Deque<Command> redoStack = new LinkedList<>();
```
The generic type for these deques should be ```Runnable``` as it is in the Wizard class under src directory | [
"command/README.md",
"localization/zh/command/README.md"
] | [
"command/README.md",
"localization/zh/command/README.md"
] | [] | diff --git a/command/README.md b/command/README.md
index 476edc47af39..a3b863b78cbe 100644
--- a/command/README.md
+++ b/command/README.md
@@ -40,8 +40,8 @@ Here's the sample code with wizard and goblin. Let's start from the `Wizard` cla
@Slf4j
public class Wizard {
- private final Deque<Command> undoStack = new LinkedList<>();
- private final Deque<Command> redoStack = new LinkedList<>();
+ private final Deque<Runnable> undoStack = new LinkedList<>();
+ private final Deque<Runnable> redoStack = new LinkedList<>();
public Wizard() {}
diff --git a/localization/zh/command/README.md b/localization/zh/command/README.md
index a36bddfa9db1..9c34bca0e08e 100644
--- a/localization/zh/command/README.md
+++ b/localization/zh/command/README.md
@@ -34,8 +34,8 @@ public class Wizard {
private static final Logger LOGGER = LoggerFactory.getLogger(Wizard.class);
- private final Deque<Command> undoStack = new LinkedList<>();
- private final Deque<Command> redoStack = new LinkedList<>();
+ private final Deque<Runnable> undoStack = new LinkedList<>();
+ private final Deque<Runnable> redoStack = new LinkedList<>();
public Wizard() {}
| null | train | test | 2023-04-01T16:53:32 | "2023-01-25T14:18:26Z" | AddeusExMachina | train |
iluwatar/java-design-patterns/2445_2518 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/2445 | iluwatar/java-design-patterns/2518 | [
"keyword_pr_to_issue"
] | cf64d6ae9a2196b0b9f190922c68e789484592eb | 4808865c0bb91c5f6a8842e77551a244945d66c3 | [
"This issue has been automatically marked as stale because it has not had recent activity. The issue will be unassigned if no further activity occurs. Thank you for your contributions.\n",
"Hey, seeing as this issue hasn't been solved I would like to give a try if it's ok.",
"This issue has been automatically marked as stale because it has not had recent activity. The issue will be unassigned if no further activity occurs. Thank you for your contributions.\n"
] | [
"<picture><img alt=\"6% of developers fix this issue\" src=\"https://lift.sonatype.com/api/commentimage/fixrate/6/display.svg\"></picture>\n\n<b>*[UnnecessarilyFullyQualified](https://errorprone.info/bugpattern/UnnecessarilyFullyQualified):</b>* This fully qualified name is unambiguous to the compiler if imported.\n\n---\n\n\n```suggestion\nGenerated\n```\n\n\n❗❗ <b>3 similar findings have been found in this PR</b>\n\n<details><summary>🔎 Expand here to view all instances of this finding</summary><br/>\n \n \n<div align=\\\"center\\\">\n\n\n| **File Path** | **Line Number** |\n| ------------- | ------------- |\n| event-sourcing/src/main/java/com/iluwatar/event/sourcing/processor/EventJournal.java | [10](https://github.com/iluwatar/java-design-patterns/blob/b88f0beba0f80885ff4d1e60d99b5acc1f146287/event-sourcing/src/main/java/com/iluwatar/event/sourcing/processor/EventJournal.java#L10) |\n| event-sourcing/src/main/java/com/iluwatar/event/sourcing/processor/EventJournal.java | [10](https://github.com/iluwatar/java-design-patterns/blob/b88f0beba0f80885ff4d1e60d99b5acc1f146287/event-sourcing/src/main/java/com/iluwatar/event/sourcing/processor/EventJournal.java#L10) |\n| event-sourcing/src/main/java/com/iluwatar/event/sourcing/processor/EventJournal.java | [10](https://github.com/iluwatar/java-design-patterns/blob/b88f0beba0f80885ff4d1e60d99b5acc1f146287/event-sourcing/src/main/java/com/iluwatar/event/sourcing/processor/EventJournal.java#L10) |\n<p><a href=\"https://lift.sonatype.com/results/github.com/iluwatar/java-design-patterns/01GZXQTRGNEZWMFTDJ3QA86Q84?t=ErrorProne|UnnecessarilyFullyQualified\" target=\"_blank\">Visit the Lift Web Console</a> to find more details in your report.</p></div></details>\n\n\n\n---\n\n<details><summary>ℹ️ Expand to see all <b>@sonatype-lift</b> commands</summary>\n\nYou can reply with the following commands. For example, reply with ***@sonatype-lift ignoreall*** to leave out all findings.\n| **Command** | **Usage** |\n| ------------- | ------------- |\n| `@sonatype-lift ignore` | Leave out the above finding from this PR |\n| `@sonatype-lift ignoreall` | Leave out all the existing findings from this PR |\n| `@sonatype-lift exclude <file\\|issue\\|path\\|tool>` | Exclude specified `file\\|issue\\|path\\|tool` from Lift findings by updating your config.toml file |\n\n**Note:** When talking to LiftBot, you need to **refresh** the page to see its response.\n<sub>[Click here](https://github.com/apps/sonatype-lift/installations/new) to add LiftBot to another repo.</sub></details>\n\n"
] | "2023-05-08T12:19:51Z" | [
"type: refactoring",
"epic: code quality",
"status: stale"
] | Refactor event sourcing | I'll refactor some codes of event sourcing pattern. The specific tasks I suggest are listed below.
- [ ] remove the use of deprecated `JsonParser`
- [ ] use jackson `ObjectMapper` instead of `Gson`
- [ ] fix some warnings checked by sonarlint | [
"event-sourcing/pom.xml",
"event-sourcing/src/main/java/com/iluwatar/event/sourcing/app/App.java",
"event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/AccountCreateEvent.java",
"event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/MoneyDepositEvent.java",
"event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/MoneyTransferEvent.java",
"event-sourcing/src/main/java/com/iluwatar/event/sourcing/processor/DomainEventProcessor.java",
"event-sourcing/src/main/java/com/iluwatar/event/sourcing/processor/JsonFileJournal.java"
] | [
"event-sourcing/pom.xml",
"event-sourcing/src/main/java/com/iluwatar/event/sourcing/app/App.java",
"event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/AccountCreateEvent.java",
"event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/MoneyDepositEvent.java",
"event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/MoneyTransferEvent.java",
"event-sourcing/src/main/java/com/iluwatar/event/sourcing/processor/DomainEventProcessor.java",
"event-sourcing/src/main/java/com/iluwatar/event/sourcing/processor/EventJournal.java",
"event-sourcing/src/main/java/com/iluwatar/event/sourcing/processor/JsonFileJournal.java"
] | [
"event-sourcing/src/test/java/IntegrationTest.java"
] | diff --git a/event-sourcing/pom.xml b/event-sourcing/pom.xml
index ae609d67e76b..569a5fceebd8 100644
--- a/event-sourcing/pom.xml
+++ b/event-sourcing/pom.xml
@@ -40,8 +40,8 @@
<scope>test</scope>
</dependency>
<dependency>
- <groupId>com.google.code.gson</groupId>
- <artifactId>gson</artifactId>
+ <groupId>com.fasterxml.jackson.core</groupId>
+ <artifactId>jackson-databind</artifactId>
</dependency>
</dependencies>
<build>
diff --git a/event-sourcing/src/main/java/com/iluwatar/event/sourcing/app/App.java b/event-sourcing/src/main/java/com/iluwatar/event/sourcing/app/App.java
index d356a8b99f8a..4b90c6ae0bdb 100644
--- a/event-sourcing/src/main/java/com/iluwatar/event/sourcing/app/App.java
+++ b/event-sourcing/src/main/java/com/iluwatar/event/sourcing/app/App.java
@@ -28,6 +28,7 @@
import com.iluwatar.event.sourcing.event.MoneyDepositEvent;
import com.iluwatar.event.sourcing.event.MoneyTransferEvent;
import com.iluwatar.event.sourcing.processor.DomainEventProcessor;
+import com.iluwatar.event.sourcing.processor.JsonFileJournal;
import com.iluwatar.event.sourcing.state.AccountAggregate;
import java.math.BigDecimal;
import java.util.Date;
@@ -42,16 +43,18 @@
* transactional data, and maintain full audit trails and history that can enable compensating
* actions.
*
- * <p>This App class is an example usage of an Event Sourcing pattern. As an example, two bank accounts
- * are created, then some money deposit and transfer actions are taken, so a new state of accounts is
- * created. At that point, state is cleared in order to represent a system shut-down. After the shut-down,
- * system state is recovered by re-creating the past events from event journals. Then state is
- * printed so a user can view the last state is same with the state before a system shut-down.
+ * <p>This App class is an example usage of an Event Sourcing pattern. As an example, two bank
+ * accounts are created, then some money deposit and transfer actions are taken, so a new state of
+ * accounts is created. At that point, state is cleared in order to represent a system shut-down.
+ * After the shut-down, system state is recovered by re-creating the past events from event
+ * journals. Then state is printed so a user can view the last state is same with the state before a
+ * system shut-down.
*
* <p>Created by Serdar Hamzaogullari on 06.08.2017.
*/
@Slf4j
public class App {
+
/**
* The constant ACCOUNT OF DAENERYS.
*/
@@ -68,8 +71,7 @@ public class App {
*/
public static void main(String[] args) {
- var eventProcessor = new DomainEventProcessor();
-
+ var eventProcessor = new DomainEventProcessor(new JsonFileJournal());
LOGGER.info("Running the system first time............");
eventProcessor.reset();
@@ -103,7 +105,7 @@ public static void main(String[] args) {
LOGGER.info("Recover the system by the events in journal file............");
- eventProcessor = new DomainEventProcessor();
+ eventProcessor = new DomainEventProcessor(new JsonFileJournal());
eventProcessor.recover();
LOGGER.info("...............Recovered State:............");
diff --git a/event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/AccountCreateEvent.java b/event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/AccountCreateEvent.java
index 9e6b40e62ee0..f3f4e78e6ab3 100644
--- a/event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/AccountCreateEvent.java
+++ b/event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/AccountCreateEvent.java
@@ -24,14 +24,15 @@
*/
package com.iluwatar.event.sourcing.event;
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonProperty;
import com.iluwatar.event.sourcing.domain.Account;
import com.iluwatar.event.sourcing.state.AccountAggregate;
import lombok.Getter;
/**
- * This is the class that implements account created event.
- * Holds the necessary info for an account created event.
- * Implements the process function that finds the event-related domain objects and
+ * This is the class that implements account created event. Holds the necessary info for an account
+ * created event. Implements the process function that finds the event-related domain objects and
* calls the related domain object's handle event functions
*
* <p>Created by Serdar Hamzaogullari on 06.08.2017.
@@ -50,7 +51,10 @@ public class AccountCreateEvent extends DomainEvent {
* @param accountNo the account no
* @param owner the owner
*/
- public AccountCreateEvent(long sequenceId, long createdTime, int accountNo, String owner) {
+ @JsonCreator
+ public AccountCreateEvent(@JsonProperty("sequenceId") long sequenceId,
+ @JsonProperty("createdTime") long createdTime,
+ @JsonProperty("accountNo") int accountNo, @JsonProperty("owner") String owner) {
super(sequenceId, createdTime, "AccountCreateEvent");
this.accountNo = accountNo;
this.owner = owner;
diff --git a/event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/MoneyDepositEvent.java b/event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/MoneyDepositEvent.java
index 96afd4640012..07e88bc0ea28 100644
--- a/event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/MoneyDepositEvent.java
+++ b/event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/MoneyDepositEvent.java
@@ -24,6 +24,8 @@
*/
package com.iluwatar.event.sourcing.event;
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonProperty;
import com.iluwatar.event.sourcing.state.AccountAggregate;
import java.math.BigDecimal;
import java.util.Optional;
@@ -50,7 +52,10 @@ public class MoneyDepositEvent extends DomainEvent {
* @param accountNo the account no
* @param money the money
*/
- public MoneyDepositEvent(long sequenceId, long createdTime, int accountNo, BigDecimal money) {
+ @JsonCreator
+ public MoneyDepositEvent(@JsonProperty("sequenceId") long sequenceId,
+ @JsonProperty("createdTime") long createdTime,
+ @JsonProperty("accountNo") int accountNo, @JsonProperty("money") BigDecimal money) {
super(sequenceId, createdTime, "MoneyDepositEvent");
this.money = money;
this.accountNo = accountNo;
diff --git a/event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/MoneyTransferEvent.java b/event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/MoneyTransferEvent.java
index 18d98cded008..3b4fa1ed1bb0 100644
--- a/event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/MoneyTransferEvent.java
+++ b/event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/MoneyTransferEvent.java
@@ -24,6 +24,8 @@
*/
package com.iluwatar.event.sourcing.event;
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonProperty;
import com.iluwatar.event.sourcing.state.AccountAggregate;
import java.math.BigDecimal;
import java.util.Optional;
@@ -52,8 +54,11 @@ public class MoneyTransferEvent extends DomainEvent {
* @param accountNoFrom the account no from
* @param accountNoTo the account no to
*/
- public MoneyTransferEvent(long sequenceId, long createdTime, BigDecimal money, int accountNoFrom,
- int accountNoTo) {
+ @JsonCreator
+ public MoneyTransferEvent(@JsonProperty("sequenceId") long sequenceId,
+ @JsonProperty("createdTime") long createdTime,
+ @JsonProperty("money") BigDecimal money, @JsonProperty("accountNoFrom") int accountNoFrom,
+ @JsonProperty("accountNoTo") int accountNoTo) {
super(sequenceId, createdTime, "MoneyTransferEvent");
this.money = money;
this.accountNoFrom = accountNoFrom;
diff --git a/event-sourcing/src/main/java/com/iluwatar/event/sourcing/processor/DomainEventProcessor.java b/event-sourcing/src/main/java/com/iluwatar/event/sourcing/processor/DomainEventProcessor.java
index e1f11eebec6b..cdfe44e336b2 100644
--- a/event-sourcing/src/main/java/com/iluwatar/event/sourcing/processor/DomainEventProcessor.java
+++ b/event-sourcing/src/main/java/com/iluwatar/event/sourcing/processor/DomainEventProcessor.java
@@ -28,13 +28,17 @@
/**
* This is the implementation of event processor. All events are processed by this class. This
- * processor uses processorJournal to persist and recover events.
+ * processor uses eventJournal to persist and recover events.
*
* <p>Created by Serdar Hamzaogullari on 06.08.2017.
*/
public class DomainEventProcessor {
- private final JsonFileJournal processorJournal = new JsonFileJournal();
+ private final EventJournal eventJournal;
+
+ public DomainEventProcessor(EventJournal eventJournal) {
+ this.eventJournal = eventJournal;
+ }
/**
* Process.
@@ -43,14 +47,14 @@ public class DomainEventProcessor {
*/
public void process(DomainEvent domainEvent) {
domainEvent.process();
- processorJournal.write(domainEvent);
+ eventJournal.write(domainEvent);
}
/**
* Reset.
*/
public void reset() {
- processorJournal.reset();
+ eventJournal.reset();
}
/**
@@ -58,7 +62,7 @@ public void reset() {
*/
public void recover() {
DomainEvent domainEvent;
- while ((domainEvent = processorJournal.readNext()) != null) {
+ while ((domainEvent = eventJournal.readNext()) != null) {
domainEvent.process();
}
}
diff --git a/event-sourcing/src/main/java/com/iluwatar/event/sourcing/processor/EventJournal.java b/event-sourcing/src/main/java/com/iluwatar/event/sourcing/processor/EventJournal.java
new file mode 100644
index 000000000000..49bc89582a13
--- /dev/null
+++ b/event-sourcing/src/main/java/com/iluwatar/event/sourcing/processor/EventJournal.java
@@ -0,0 +1,37 @@
+package com.iluwatar.event.sourcing.processor;
+
+import com.iluwatar.event.sourcing.event.DomainEvent;
+import java.io.File;
+import lombok.extern.slf4j.Slf4j;
+
+/**
+ * Base class for Journaling implementations.
+ */
+@Slf4j
+public abstract class EventJournal {
+
+ File file;
+
+ /**
+ * Write.
+ *
+ * @param domainEvent the domain event.
+ */
+ abstract void write(DomainEvent domainEvent);
+
+ /**
+ * Reset.
+ */
+ void reset() {
+ if (file.delete()) {
+ LOGGER.info("File cleared successfully............");
+ }
+ }
+
+ /**
+ * Read domain event.
+ *
+ * @return the domain event.
+ */
+ abstract DomainEvent readNext();
+}
diff --git a/event-sourcing/src/main/java/com/iluwatar/event/sourcing/processor/JsonFileJournal.java b/event-sourcing/src/main/java/com/iluwatar/event/sourcing/processor/JsonFileJournal.java
index 048e270e2eaa..cfde566dc2fb 100644
--- a/event-sourcing/src/main/java/com/iluwatar/event/sourcing/processor/JsonFileJournal.java
+++ b/event-sourcing/src/main/java/com/iluwatar/event/sourcing/processor/JsonFileJournal.java
@@ -24,9 +24,8 @@
*/
package com.iluwatar.event.sourcing.processor;
-import com.google.gson.Gson;
-import com.google.gson.JsonElement;
-import com.google.gson.JsonParser;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
import com.iluwatar.event.sourcing.event.AccountCreateEvent;
import com.iluwatar.event.sourcing.event.DomainEvent;
import com.iluwatar.event.sourcing.event.MoneyDepositEvent;
@@ -49,9 +48,8 @@
*
* <p>Created by Serdar Hamzaogullari on 06.08.2017.
*/
-public class JsonFileJournal {
+public class JsonFileJournal extends EventJournal {
- private final File file;
private final List<String> events = new ArrayList<>();
private int index = 0;
@@ -81,22 +79,12 @@ public JsonFileJournal() {
*
* @param domainEvent the domain event
*/
+ @Override
public void write(DomainEvent domainEvent) {
- var gson = new Gson();
- JsonElement jsonElement;
- if (domainEvent instanceof AccountCreateEvent) {
- jsonElement = gson.toJsonTree(domainEvent, AccountCreateEvent.class);
- } else if (domainEvent instanceof MoneyDepositEvent) {
- jsonElement = gson.toJsonTree(domainEvent, MoneyDepositEvent.class);
- } else if (domainEvent instanceof MoneyTransferEvent) {
- jsonElement = gson.toJsonTree(domainEvent, MoneyTransferEvent.class);
- } else {
- throw new RuntimeException("Journal Event not recognized");
- }
-
+ var mapper = new ObjectMapper();
try (var output = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(file, true), StandardCharsets.UTF_8))) {
- var eventString = jsonElement.toString();
+ var eventString = mapper.writeValueAsString(domainEvent);
output.write(eventString + "\r\n");
} catch (IOException e) {
throw new RuntimeException(e);
@@ -104,14 +92,6 @@ public void write(DomainEvent domainEvent) {
}
- /**
- * Reset.
- */
- public void reset() {
- file.delete();
- }
-
-
/**
* Read the next domain event.
*
@@ -124,19 +104,19 @@ public DomainEvent readNext() {
var event = events.get(index);
index++;
- var parser = new JsonParser();
- var jsonElement = parser.parse(event);
- var eventClassName = jsonElement.getAsJsonObject().get("eventClassName").getAsString();
- var gson = new Gson();
+ var mapper = new ObjectMapper();
DomainEvent domainEvent;
- if (eventClassName.equals("AccountCreateEvent")) {
- domainEvent = gson.fromJson(jsonElement, AccountCreateEvent.class);
- } else if (eventClassName.equals("MoneyDepositEvent")) {
- domainEvent = gson.fromJson(jsonElement, MoneyDepositEvent.class);
- } else if (eventClassName.equals("MoneyTransferEvent")) {
- domainEvent = gson.fromJson(jsonElement, MoneyTransferEvent.class);
- } else {
- throw new RuntimeException("Journal Event not recegnized");
+ try {
+ var jsonElement = mapper.readTree(event);
+ var eventClassName = jsonElement.get("eventClassName").asText();
+ domainEvent = switch (eventClassName) {
+ case "AccountCreateEvent" -> mapper.treeToValue(jsonElement, AccountCreateEvent.class);
+ case "MoneyDepositEvent" -> mapper.treeToValue(jsonElement, MoneyDepositEvent.class);
+ case "MoneyTransferEvent" -> mapper.treeToValue(jsonElement, MoneyTransferEvent.class);
+ default -> throw new RuntimeException("Journal Event not recognized");
+ };
+ } catch (JsonProcessingException jsonProcessingException) {
+ throw new RuntimeException("Failed to convert JSON");
}
domainEvent.setRealTime(false);
| diff --git a/event-sourcing/src/test/java/IntegrationTest.java b/event-sourcing/src/test/java/IntegrationTest.java
index 9e15a2163bcc..c737bd0da43d 100644
--- a/event-sourcing/src/test/java/IntegrationTest.java
+++ b/event-sourcing/src/test/java/IntegrationTest.java
@@ -22,6 +22,7 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
+
import static com.iluwatar.event.sourcing.app.App.ACCOUNT_OF_DAENERYS;
import static com.iluwatar.event.sourcing.app.App.ACCOUNT_OF_JON;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -30,6 +31,7 @@
import com.iluwatar.event.sourcing.event.MoneyDepositEvent;
import com.iluwatar.event.sourcing.event.MoneyTransferEvent;
import com.iluwatar.event.sourcing.processor.DomainEventProcessor;
+import com.iluwatar.event.sourcing.processor.JsonFileJournal;
import com.iluwatar.event.sourcing.state.AccountAggregate;
import java.math.BigDecimal;
import java.util.Date;
@@ -53,7 +55,7 @@ class IntegrationTest {
*/
@BeforeEach
void initialize() {
- eventProcessor = new DomainEventProcessor();
+ eventProcessor = new DomainEventProcessor(new JsonFileJournal());
}
/**
@@ -84,7 +86,7 @@ void testStateRecovery() {
AccountAggregate.resetState();
- eventProcessor = new DomainEventProcessor();
+ eventProcessor = new DomainEventProcessor(new JsonFileJournal());
eventProcessor.recover();
var accountOfDaenerysAfterShotDown = AccountAggregate.getAccount(ACCOUNT_OF_DAENERYS);
| test | test | 2023-05-06T11:10:06 | "2023-01-09T14:06:20Z" | hwan33 | train |
iluwatar/java-design-patterns/2286_2533 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/2286 | iluwatar/java-design-patterns/2533 | [
"timestamp(timedelta=5.0, similarity=0.8479848449633892)",
"keyword_pr_to_issue"
] | cf64d6ae9a2196b0b9f190922c68e789484592eb | 376cd215274d7f9ecb8bc90b1d35e36d567b1654 | [
"I want to participate."
] | [
"should be Creational"
] | "2023-06-04T11:22:13Z" | [
"info: help wanted",
"type: feature",
"epic: documentation"
] | Translation to Russian | This task tracks the translation of the patterns. More information about the translation process is available at https://github.com/iluwatar/java-design-patterns/wiki/15.-Support-for-multiple-languages
Acceptance criteria
- The patterns have been translated
- The patterns can be browsed in Github and on the website https://java-design-patterns.com
| [] | [
"localization/ru/abstract-factory/README.md"
] | [] | diff --git a/localization/ru/abstract-factory/README.md b/localization/ru/abstract-factory/README.md
new file mode 100644
index 000000000000..044e03c53c5c
--- /dev/null
+++ b/localization/ru/abstract-factory/README.md
@@ -0,0 +1,237 @@
+---
+title: Abstract Factory
+category: Creational
+language: ru
+tag:
+ - Gang of Four
+---
+
+## Альтернативные названия
+Kit
+
+## Цель
+Предоставление интерфейса для создания семейств взаимосвязанных или взаимозависимых объектов без указания их конкретных классов.
+
+## Объяснение
+Пример из реального мира:
+> Представьте, что вы хотите создать королевство с замком, королём и армией. Эльфийскому королевству понадобится эльфийский замок, эльфийский король и эльфийская армия, в то время как оркскому королевству понадобится оркский замок, оркский король и оркская армия. Между объектами королевства существует взаимозависимость.
+
+Простыми словами:
+> Фабрика фабрик; фабрика, которая объединяет отдельные, но взаимозависимые/взаимозаменяемые фабрики без указания их конкретных классов.
+
+Википедия пишет:
+> Порождающий шаблон проектирования, предоставляет интерфейс для создания семейств взаимосвязанных или взаимозависимых объектов, не специфицируя их конкретных классов.
+
+**Программный пример**\
+Основываясь на примере королевства выше, во-первых, нам понадобятся интерфейсы и реализации для объектов в королевстве.
+
+```java
+public interface Castle {
+ String getDescription();
+}
+
+public interface King {
+ String getDescription();
+}
+
+public interface Army {
+ String getDescription();
+}
+
+// Эльфийская реализация
+public class ElfCastle implements Castle {
+ static final String DESCRIPTION = "Это эльфийский замок!";
+ @Override
+ public String getDescription() {
+ return DESCRIPTION;
+ }
+}
+public class ElfKing implements King {
+ static final String DESCRIPTION = "Это эльфийский король!";
+ @Override
+ public String getDescription() {
+ return DESCRIPTION;
+ }
+}
+public class ElfArmy implements Army {
+ static final String DESCRIPTION = "Это эльфийская армия!";
+ @Override
+ public String getDescription() {
+ return DESCRIPTION;
+ }
+}
+
+// Оркская реализация
+public class OrcCastle implements Castle {
+ static final String DESCRIPTION = "Это оркский замок!";
+ @Override
+ public String getDescription() {
+ return DESCRIPTION;
+ }
+}
+public class OrcKing implements King {
+ static final String DESCRIPTION = "Это оркский король!";
+ @Override
+ public String getDescription() {
+ return DESCRIPTION;
+ }
+}
+public class OrcArmy implements Army {
+ static final String DESCRIPTION = "Это оркская армия!";
+ @Override
+ public String getDescription() {
+ return DESCRIPTION;
+ }
+}
+```
+
+Во-вторых, нам понадобятся абстракция фабрики королевства, а также реализации этой абстракции:
+
+```java
+public interface KingdomFactory {
+ Castle createCastle();
+ King createKing();
+ Army createArmy();
+}
+
+public class ElfKingdomFactory implements KingdomFactory {
+
+ @Override
+ public Castle createCastle() {
+ return new ElfCastle();
+ }
+
+ @Override
+ public King createKing() {
+ return new ElfKing();
+ }
+
+ @Override
+ public Army createArmy() {
+ return new ElfArmy();
+ }
+}
+
+public class OrcKingdomFactory implements KingdomFactory {
+
+ @Override
+ public Castle createCastle() {
+ return new OrcCastle();
+ }
+
+ @Override
+ public King createKing() {
+ return new OrcKing();
+ }
+
+ @Override
+ public Army createArmy() {
+ return new OrcArmy();
+ }
+}
+```
+
+На данный момент, у нас есть абстрактная фабрика, которая позволяет создавать семейство взаимосвязанных объектов, то есть фабрика эльфийского королевства создаёт эльфийский замок, эльфийского короля, эльфийскую армию и так далее:
+
+```java
+var factory = new ElfKingdomFactory();
+var castle = factory.createCastle();
+var king = factory.createKing();
+var army = factory.createArmy();
+
+castle.getDescription();
+king.getDescription();
+army.getDescription();
+```
+
+Вывод программы:
+
+```
+Это эльфийский замок!
+Это эльфийский король!
+Это эльфийская армия!
+```
+
+Можно спроектировать фабрику для наших различных фабрик королевств. В следующем примере, мы создали `FactoryMaker`, который ответственен за создание экземпляра `ElfKingdomFactory`, либо `OrcKingdomFactory`.
+
+Клиент может использовать класс `FactoryMaker`, чтобы создать желаемую конкретную фабрику, которая в свою очередь будет производить разные конкретные объекты, унаследованные от `Castle`, `King`, `Army`.
+
+В этом примере использовано перечисление, чтобы параметризовать то, какую фабрику королевства запрашивает клиент:
+
+```java
+public static class FactoryMaker {
+ public enum KingdomType {
+ ELF, ORC
+ }
+
+ public static KingdomFactory makeFactory(KingdomType type) {
+ return switch (type) {
+ case ELF -> new ElfKingdomFactory();
+ case ORC -> new OrcKingdomFactory();
+ default -> throe new IllegalArgumentException("Данный тип королества не поддерживается.")
+ }
+ }
+}
+
+ public static void main(String[] args) {
+ var app = new App();
+
+ LOGGER.info("Эльфийское королевство");
+ app.createKingdom(FactoryMaker.makeFactory(KingdomType.ELF));
+ LOGGER.indo(app.getCastle().getDescription());
+ LOGGER.indo(app.getKinv().getDescription());
+ LOGGER.indo(app.getArmy().getDescription());
+
+ LOGGER.info("Оркское королевство");
+
+ app.createKingdom(FactoryMaker.makeFactory(KingdomType.ORC));
+ LOGGER.indo(app.getCastle().getDescription());
+ LOGGER.indo(app.getKinv().getDescription());
+ LOGGER.indo(app.getArmy().getDescription());
+ }
+
+```
+
+## Диаграмма классов
+![Диаграмма классов паттерна проектирования абстрактная фабрика](../../../abstract-factory/etc/abstract-factory.urm.png)
+
+## Применимость
+Используйте шаблон проектирования абстрактная фабрика, когда:
+
+- Система должна быть независимой от того, как создаются, составляются и представляются её продукты;
+- Система должна быть сконфигурирована одним из нескольких семейств продуктов;
+- Семейство связанных продуктов спроектировано для совместного использования и вам необходимо обеспечить соблюдение данного ограничения;
+- Вы хотите предоставить библиотеку классов, но готовы раскрыть только их интерфейсы, но не реализацию;
+- Время жизни зависимости концептуально короче, чем время жизни потребителя;
+- Вам требуется значение времени исполнения, чтобы создать требуемую зависимость;
+- Вы хотите решить какие продукты из семейства вам нужны во время исполнения;
+- Вам нужно предоставить один или несколько параметров, которые известны только во время исполнения прежде, чем вы сможете решить зависимость;
+- В случае, когда требуется последовательность среди продуктов;
+- Вы не хотите менять существующий код, когда добавляются новые продукты или семейство продуктов в программе.
+
+Примеры сценариев использования:
+
+- Выбор необходимой реализации FileSystemAcmeService или DataBaseAcmeSerivce или NetworkAcmeService во времени выполнения;
+- Написание модульных тестов становится намного легче;
+- Элементы графического пользовательского интерфейса для различных операционных систем.
+
+## Следствия
+- Внедрение зависимости в Java скрывает зависимости класса, приводящие к ошибкам времени выполнения, которые могли-бы быть обнаружены во времени компиляции;
+- Данный паттерн проектирования отлично справляется с задачей создания уже определённых объектов, но добавление новых может быть трудоёмким;
+- Код становится сложнее, чем ему следует из-за появления большого количества новых интерфейсов и классов, которые появляются вместе с этим паттерном проектирования.
+
+## Руководства
+* [Abstract Factory Pattern Tutorial](https://www.journaldev.com/1418/abstract-factory-design-pattern-in-java)
+
+## Известные применения
+* [javax.xml.parsers.DocumentBuilderFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/parsers/DocumentBuilderFactory.html)
+* [javax.xml.transform.TransformerFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/transform/TransformerFactory.html#newInstance--)
+* [javax.xml.xpath.XPathFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/xpath/XPathFactory.html#newInstance--)
+
+## Родственные паттерны проектирования
+* [Factory Method](https://java-design-patterns.com/patterns/factory-method/)
+* [Factory Kit](https://java-design-patterns.com/patterns/factory-kit/)
+
+## Благодарности
+* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59)
+* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b)
| null | train | test | 2023-05-06T11:10:06 | "2022-10-30T08:12:16Z" | iluwatar | train |
iluwatar/java-design-patterns/187_2538 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/187 | iluwatar/java-design-patterns/2538 | [
"keyword_pr_to_issue"
] | 72f7fcab0ea5677e39a8cc064e1c69527a0c309c | 1894fcf175a227028cdff4f359e2dbabe0ec36ff | [
"@iluwatar There is an issue #188 where concern regarding lazy loading of Singleton is raised. I was going through the singleton documentation yesterday and found that the disadvantages of approaches are not discussed. We should document that the lazy loading example with `synchronized` keyword is ok for small applications but actually is too slow for production and should not be preferred.\n",
"http://programmers.stackexchange.com/questions/179386/what-are-the-downsides-of-implementing-a-singleton-with-javas-enum covers downsides of `Enum` based singleton.\n",
"Misko Hevery has discussed Singleton vs single instance in this blog post http://misko.hevery.com/2008/08/25/root-cause-of-singletons/\nIn his blog Misko discusses that there is nothing wrong in having a single instance of something, like having a single application scope object maintained by IoC containers, they don't have private constructors or global instance variable. The singletonness is maintained by container. We can also include this in FAQ \"Are Singletons bad?\" or some better name.\nFurther references which I found useful:\n- http://misko.hevery.com/2008/08/17/singletons-are-pathological-liars/\n- http://misko.hevery.com/2008/08/21/where-have-all-the-singletons-gone/\n- http://stackoverflow.com/questions/137975/what-is-so-bad-about-singletons\n\nI feel much can be said about Singletons so we need to figure out how we are going to address this. Your thoughts?\n",
"I haven't read those links yet but by my own experience I know that in some simple scenarios a singleton can be perfectly replaced by a uninstantiable class. I think this should be written as a footnote somewhere if we already have a place for these things.\n",
"There are interesting findings in the Oracle's article particularly about double-checked locking. However, I think our implementation [ThreadSafeDoubleCheckLocking](https://github.com/iluwatar/java-design-patterns/blob/master/singleton/src/main/java/com/iluwatar/singleton/ThreadSafeDoubleCheckLocking.java) is correct.\n",
"Those are excellent articles @npathai :+1: Thanks for sharing.\n",
"@iluwatar Is there an implementation of Singleton with Enum in this repo ? I think Effective Java recommends that we use Enum as Singleton as it is the most bulletproof construction of singleton.\n\nEdit:- There is one...saw it just now.\n",
"Yes but there are known downsides for that. EJ is old and much have been learned since then.\n\nAn issue is that it will have the following public static methods:\n\n```\n public static Foo[] values()\n public static Foo valueOf(String name)\n```\n",
"http://stackoverflow.com/questions/137975/what-is-so-bad-about-singletons\n",
"@iluwatar I had linked this question in my previous comment. :+1: though. \n",
"Ah, didn't notice that. This thread is getting long...\n",
"@iluwatar is this task still open. Can you assign this to me? \r\nI am reading about singletons\r\nTask is: \"Improve Singleton examples and their documentation where necessary.\" ?",
"Great, go ahead @sanghisha145 ",
"> @iluwatar is this task still open. Can you assign this to me?\r\n> I am reading about singletons\r\n> Task is: \"Improve Singleton examples and their documentation where necessary.\" ?\r\n\r\nHey @sanghisha145, Any updates?",
"hey @iluwatar , @ohbus is this issue still open. You can assign this to me. \r\nI will try to finish it within 1 month.\r\nand I will ask for help if necessary from you all.",
"After a long period of not receiving any updates from @sanghisha145\r\n\r\nI am assigning this issue to @Vikashratn.\r\n\r\nGood Luck!! ",
"@Vikashratn are you working on this?",
"hey @Vikashratn are u still working on this issue\r\n",
"This issue is free for taking again.",
"```java\r\npublic class Element {\r\n\tpublic static final Element NONE = new Element();\r\n\tpublic static final Element WATER = new Water();\r\n\tpublic static final Element EARTH = new Earth();\r\n\tpublic static final Element FIRE = new Fire();\r\n\tpublic static final Element AIR = new Air();\r\n\t\r\n\tpublic void printName() {\r\n\t\tSystem.out.println(\"Element is: \"+getName());\r\n\t}\r\n\t\r\n\tpublic String getName() {\r\n\t\treturn \"None\";\r\n\t}\r\n}\r\npublic class Water extends Element {\r\n\tpublic String getName() {\r\n\t\treturn \"Water\";\r\n\t}\r\n}\r\npublic class Earth extends Element {\r\n\tpublic String getName() {\r\n\t\treturn \"Earth\";\r\n\t}\r\n}\r\npublic class Fire extends Element {\r\n\tpublic String getName() {\r\n\t\treturn \"Fire\";\r\n\t}\r\n}\r\npublic class Air extends Element {\r\n\tpublic String getName() {\r\n\t\treturn \"Air\";\r\n\t}\r\n}\r\n```\r\n\r\nWhy isn't something like this included in the singleton as a option?\r\nYes you could create more instances from that class, but this unique instance is technically also a singleton.\r\nWhich you can identify.\r\n\r\nIt provides a aspect that enums can not provide. If you have singleton instances that require expand ability, adding new elements (singletons) later, is not possible with enums without having resort to something like reflection/asm.\r\n\r\nofcourse you could just move functions from the enum into a interface too and let the enum extend them and have multiple enums.\r\n\r\nAlso this singleton pattern shown here is also really powerful with the factory pattern.\r\nWithout the enum overhead that exists.",
"Hi, I'm new to this project. How would i go about contributing to it?Thanks.",
"@OtherHorizon see https://github.com/iluwatar/java-design-patterns/wiki/01.-How-to-contribute",
"Is this issue still free so I can be assigned? recently I was reading about the design pattern and I want to contribute.\r\n@ohbus @iluwatar ",
"Ok @Omar-ahmed314, this is assigned for you",
"Thank you for considering me, @iluwatar , may I know the deadline for this issue? away from the deadline of hacktoberfest",
"I'd be happy for you if you completed it during the hacktober month 😀",
"This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.\n",
"We should document Bill Pugh's singleton solution",
"@iluwatar, I would like to contribute, can I be assigned to this issue? ",
"That's excellent, please go ahead @jasokolowska ",
"This issue has been automatically marked as stale because it has not had recent activity. The issue will be unassigned if no further activity occurs. Thank you for your contributions.\n",
"@iluwatar I think in the current Singleton example we are just missing Bill Pugh's singleton solution. I'm happy to take over if needed ",
"This issue has been automatically marked as stale because it has not had recent activity. The issue will be unassigned if no further activity occurs. Thank you for your contributions.\n"
] | [
"<picture><img alt=\"6% of developers fix this issue\" src=\"https://lift.sonatype.com/api/commentimage/fixrate/6/display.svg\"></picture>\n\n<b>*[ObjectToString](https://errorprone.info/bugpattern/ObjectToString):</b>* BillPughImplementation is final and does not override Object.toString, so converting it to a string will print its identity (e.g. `BillPughImplementation@4488aabb`) instead of useful information.\n\n---\n\n<details><summary>ℹ️ Expand to see all <b>@sonatype-lift</b> commands</summary>\n\nYou can reply with the following commands. For example, reply with ***@sonatype-lift ignoreall*** to leave out all findings.\n| **Command** | **Usage** |\n| ------------- | ------------- |\n| `@sonatype-lift ignore` | Leave out the above finding from this PR |\n| `@sonatype-lift ignoreall` | Leave out all the existing findings from this PR |\n| `@sonatype-lift exclude <file\\|issue\\|path\\|tool>` | Exclude specified `file\\|issue\\|path\\|tool` from Lift findings by updating your config.toml file |\n\n**Note:** When talking to LiftBot, you need to **refresh** the page to see its response.\n<sub>[Click here](https://github.com/apps/sonatype-lift/installations/new) to add LiftBot to another repo.</sub></details>\n\n",
"<picture><img alt=\"6% of developers fix this issue\" src=\"https://lift.sonatype.com/api/commentimage/fixrate/6/display.svg\"></picture>\n\n<b>*[ObjectToString](https://errorprone.info/bugpattern/ObjectToString):</b>* BillPughImplementation is final and does not override Object.toString, so converting it to a string will print its identity (e.g. `BillPughImplementation@4488aabb`) instead of useful information.\n\n---\n\n<details><summary>ℹ️ Expand to see all <b>@sonatype-lift</b> commands</summary>\n\nYou can reply with the following commands. For example, reply with ***@sonatype-lift ignoreall*** to leave out all findings.\n| **Command** | **Usage** |\n| ------------- | ------------- |\n| `@sonatype-lift ignore` | Leave out the above finding from this PR |\n| `@sonatype-lift ignoreall` | Leave out all the existing findings from this PR |\n| `@sonatype-lift exclude <file\\|issue\\|path\\|tool>` | Exclude specified `file\\|issue\\|path\\|tool` from Lift findings by updating your config.toml file |\n\n**Note:** When talking to LiftBot, you need to **refresh** the page to see its response.\n<sub>[Click here](https://github.com/apps/sonatype-lift/installations/new) to add LiftBot to another repo.</sub></details>\n\n"
] | "2023-06-18T08:34:09Z" | [
"type: enhancement",
"info: good first issue",
"epic: design",
"status: stale"
] | More Singleton wisdom | Analyze the following article from Oracle: https://community.oracle.com/docs/DOC-918906
Improve Singleton examples and their documentation where necessary.
| [
"singleton/src/main/java/com/iluwatar/singleton/App.java",
"singleton/src/main/java/com/iluwatar/singleton/EnumIvoryTower.java",
"singleton/src/main/java/com/iluwatar/singleton/InitializingOnDemandHolderIdiom.java",
"singleton/src/main/java/com/iluwatar/singleton/ThreadSafeDoubleCheckLocking.java",
"singleton/src/main/java/com/iluwatar/singleton/ThreadSafeLazyLoadedIvoryTower.java"
] | [
"singleton/src/main/java/com/iluwatar/singleton/App.java",
"singleton/src/main/java/com/iluwatar/singleton/BillPughImplementation.java",
"singleton/src/main/java/com/iluwatar/singleton/EnumIvoryTower.java",
"singleton/src/main/java/com/iluwatar/singleton/InitializingOnDemandHolderIdiom.java",
"singleton/src/main/java/com/iluwatar/singleton/ThreadSafeDoubleCheckLocking.java",
"singleton/src/main/java/com/iluwatar/singleton/ThreadSafeLazyLoadedIvoryTower.java",
"singleton/src/main/java/com/iluwatar/singleton/package-info.java"
] | [
"singleton/src/test/java/com/iluwatar/singleton/BillPughImplementationTest.java"
] | diff --git a/singleton/src/main/java/com/iluwatar/singleton/App.java b/singleton/src/main/java/com/iluwatar/singleton/App.java
index af09a7ec6828..8d7946cae95d 100644
--- a/singleton/src/main/java/com/iluwatar/singleton/App.java
+++ b/singleton/src/main/java/com/iluwatar/singleton/App.java
@@ -100,5 +100,11 @@ public static void main(String[] args) {
LOGGER.info(demandHolderIdiom.toString());
var demandHolderIdiom2 = InitializingOnDemandHolderIdiom.getInstance();
LOGGER.info(demandHolderIdiom2.toString());
+
+ // initialize singleton using Bill Pugh's implementation
+ var billPughSingleton = BillPughImplementation.getInstance();
+ LOGGER.info(billPughSingleton.toString());
+ var billPughSingleton2 = BillPughImplementation.getInstance();
+ LOGGER.info(billPughSingleton2.toString());
}
}
diff --git a/singleton/src/main/java/com/iluwatar/singleton/BillPughImplementation.java b/singleton/src/main/java/com/iluwatar/singleton/BillPughImplementation.java
new file mode 100644
index 000000000000..ba66386181df
--- /dev/null
+++ b/singleton/src/main/java/com/iluwatar/singleton/BillPughImplementation.java
@@ -0,0 +1,73 @@
+/*
+ * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
+ *
+ * The MIT License
+ * Copyright © 2014-2022 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+package com.iluwatar.singleton;
+
+/**
+ * <p>Bill Pugh Singleton Implementation.</p>
+ *
+ * <p>This implementation of the singleton design pattern takes advantage of the
+ * Java memory model's guarantees about class initialization. Each class is
+ * initialized only once, when it is first used. If the class hasn't been used
+ * yet, it won't be loaded into memory, and no memory will be allocated for
+ * a static instance. This makes the singleton instance lazy-loaded and thread-safe.</p>
+ *
+ * @author owen.leung2@gmail.com
+ */
+public final class BillPughImplementation {
+
+ /**
+ * Private constructor to prevent instantiation from outside the class.
+ */
+ private BillPughImplementation() {
+ // private constructor
+ }
+
+ /**
+ * The InstanceHolder is a static inner class and it holds the Singleton instance.
+ * It is not loaded into memory until the getInstance() method is called.
+ */
+ private static class InstanceHolder {
+ /**
+ * Singleton instance of the class.
+ */
+ private static BillPughImplementation instance = new BillPughImplementation();
+ }
+
+ /**
+ * Public accessor for the singleton instance.
+ *
+ * <p>
+ * When this method is called, the InstanceHolder is loaded into memory
+ * and creates the Singleton instance. This method provides a global access point
+ * for the singleton instance.
+ * </p>
+ *
+ * @return an instance of the class.
+ */
+ // global access point
+ public static BillPughImplementation getInstance() {
+ return InstanceHolder.instance;
+ }
+}
diff --git a/singleton/src/main/java/com/iluwatar/singleton/EnumIvoryTower.java b/singleton/src/main/java/com/iluwatar/singleton/EnumIvoryTower.java
index c98157997f90..8130dc55dd70 100644
--- a/singleton/src/main/java/com/iluwatar/singleton/EnumIvoryTower.java
+++ b/singleton/src/main/java/com/iluwatar/singleton/EnumIvoryTower.java
@@ -32,6 +32,9 @@
*/
public enum EnumIvoryTower {
+ /**
+ * The singleton instance of the class, created by the Java enum singleton pattern.
+ */
INSTANCE;
@Override
diff --git a/singleton/src/main/java/com/iluwatar/singleton/InitializingOnDemandHolderIdiom.java b/singleton/src/main/java/com/iluwatar/singleton/InitializingOnDemandHolderIdiom.java
index 013d01722796..6cff5b561a92 100644
--- a/singleton/src/main/java/com/iluwatar/singleton/InitializingOnDemandHolderIdiom.java
+++ b/singleton/src/main/java/com/iluwatar/singleton/InitializingOnDemandHolderIdiom.java
@@ -58,6 +58,10 @@ public static InitializingOnDemandHolderIdiom getInstance() {
* Provides the lazy-loaded Singleton instance.
*/
private static class HelperHolder {
+
+ /**
+ * Singleton instance of the class.
+ */
private static final InitializingOnDemandHolderIdiom INSTANCE =
new InitializingOnDemandHolderIdiom();
}
diff --git a/singleton/src/main/java/com/iluwatar/singleton/ThreadSafeDoubleCheckLocking.java b/singleton/src/main/java/com/iluwatar/singleton/ThreadSafeDoubleCheckLocking.java
index 47c01c030334..e409432a1945 100644
--- a/singleton/src/main/java/com/iluwatar/singleton/ThreadSafeDoubleCheckLocking.java
+++ b/singleton/src/main/java/com/iluwatar/singleton/ThreadSafeDoubleCheckLocking.java
@@ -34,7 +34,9 @@
* @author mortezaadi@gmail.com
*/
public final class ThreadSafeDoubleCheckLocking {
-
+ /**
+ * Singleton instance of the class, declared as volatile to ensure atomic access by multiple threads.
+ */
private static volatile ThreadSafeDoubleCheckLocking instance;
/**
@@ -73,7 +75,8 @@ public static ThreadSafeDoubleCheckLocking getInstance() {
// The instance is still not initialized so we can safely
// (no other thread can enter this zone)
// create an instance and make it our singleton instance.
- instance = result = new ThreadSafeDoubleCheckLocking();
+ result = new ThreadSafeDoubleCheckLocking();
+ instance = result;
}
}
}
diff --git a/singleton/src/main/java/com/iluwatar/singleton/ThreadSafeLazyLoadedIvoryTower.java b/singleton/src/main/java/com/iluwatar/singleton/ThreadSafeLazyLoadedIvoryTower.java
index 559363a6c998..4d1c25739673 100644
--- a/singleton/src/main/java/com/iluwatar/singleton/ThreadSafeLazyLoadedIvoryTower.java
+++ b/singleton/src/main/java/com/iluwatar/singleton/ThreadSafeLazyLoadedIvoryTower.java
@@ -31,8 +31,14 @@
*/
public final class ThreadSafeLazyLoadedIvoryTower {
+ /**
+ * Singleton instance of the class, declared as volatile to ensure atomic access by multiple threads.
+ */
private static volatile ThreadSafeLazyLoadedIvoryTower instance;
+ /**
+ * Private constructor to prevent instantiation from outside the class.
+ */
private ThreadSafeLazyLoadedIvoryTower() {
// Protect against instantiation via reflection
if (instance != null) {
@@ -42,6 +48,8 @@ private ThreadSafeLazyLoadedIvoryTower() {
/**
* The instance doesn't get created until the method is called for the first time.
+ *
+ * @return an instance of the class.
*/
public static synchronized ThreadSafeLazyLoadedIvoryTower getInstance() {
if (instance == null) {
diff --git a/singleton/src/main/java/com/iluwatar/singleton/package-info.java b/singleton/src/main/java/com/iluwatar/singleton/package-info.java
new file mode 100644
index 000000000000..bfcfbd77e344
--- /dev/null
+++ b/singleton/src/main/java/com/iluwatar/singleton/package-info.java
@@ -0,0 +1,25 @@
+/*
+ * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
+ *
+ * The MIT License
+ * Copyright © 2014-2022 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+package com.iluwatar.singleton;
| diff --git a/singleton/src/test/java/com/iluwatar/singleton/BillPughImplementationTest.java b/singleton/src/test/java/com/iluwatar/singleton/BillPughImplementationTest.java
new file mode 100644
index 000000000000..90a3424e412c
--- /dev/null
+++ b/singleton/src/test/java/com/iluwatar/singleton/BillPughImplementationTest.java
@@ -0,0 +1,16 @@
+package com.iluwatar.singleton;
+
+/**
+ * Date: 06/18/23 - 16:29 PM.
+ *
+ * @author Owen Leung
+ */
+public class BillPughImplementationTest
+ extends SingletonTest<BillPughImplementation>{
+ /**
+ * Create a new singleton test instance using the given 'getInstance' method.
+ */
+ public BillPughImplementationTest() {
+ super(BillPughImplementation::getInstance);
+ }
+}
| val | test | 2023-07-11T12:04:10 | "2015-08-04T16:25:38Z" | iluwatar | train |
iluwatar/java-design-patterns/2544_2545 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/2544 | iluwatar/java-design-patterns/2545 | [
"timestamp(timedelta=639.0, similarity=0.9117834642299325)"
] | 72f7fcab0ea5677e39a8cc064e1c69527a0c309c | 2154e777b6a7d992058197cfea823e969bb64f9c | [
"I'm working on it",
"1: at line no 66(var bubblesToCheck = bubbles.values();) and at ln :70 you are iterating it (bubbles.forEach) and inside handleCollision() method you are updating the same map(bubbles,inside pop() allBubbles.remove(this.id);) . \r\nThats why once you get the iterator from a collection you can not modify the collection(if map changes the babbles.values() also affected).\r\n2:same for withSpatialPartition() method LN:93 bubbles.forEach\r\n3: same for noSpatialPartition() method LN 70:bubbles.forEach\r\n"
] | [] | "2023-06-27T15:23:01Z" | [
"type: bug",
"epic: pattern"
] | [Spatial Partition] Error when run App.java | When run [App.java](https://github.com/iluwatar/java-design-patterns/blob/5b147b00367a500e8dfeac882d4b0d6a0540c6b9/spatial-partition/src/main/java/com/iluwatar/spatialpartition/App.java), there are some problems:
- `ConcurrentModificationException` happen:
```
Exception in thread "main" java.util.ConcurrentModificationException
at java.base/java.util.HashMap$HashIterator.nextNode(HashMap.java:1597)
at java.base/java.util.HashMap$ValueIterator.next(HashMap.java:1625)
at com.iluwatar.spatialpartition.Bubble.handleCollision(Bubble.java:69)
at com.iluwatar.spatialpartition.App.lambda$noSpatialPartition$0(App.java:75)
at java.base/java.util.HashMap.forEach(HashMap.java:1421)
at com.iluwatar.spatialpartition.App.noSpatialPartition(App.java:70)
at com.iluwatar.spatialpartition.App.main(App.java:125)
```
- Some logs don't work, just log `"Bubble"`
- Some logs don't use Slf4j formatting anchor _{}_. | [
"spatial-partition/src/main/java/com/iluwatar/spatialpartition/App.java",
"spatial-partition/src/main/java/com/iluwatar/spatialpartition/Bubble.java",
"spatial-partition/src/main/java/com/iluwatar/spatialpartition/Point.java",
"spatial-partition/src/main/java/com/iluwatar/spatialpartition/QuadTree.java",
"spatial-partition/src/main/java/com/iluwatar/spatialpartition/SpatialPartitionBubbles.java",
"spatial-partition/src/main/java/com/iluwatar/spatialpartition/SpatialPartitionGeneric.java"
] | [
"spatial-partition/src/main/java/com/iluwatar/spatialpartition/App.java",
"spatial-partition/src/main/java/com/iluwatar/spatialpartition/Bubble.java",
"spatial-partition/src/main/java/com/iluwatar/spatialpartition/Point.java",
"spatial-partition/src/main/java/com/iluwatar/spatialpartition/QuadTree.java",
"spatial-partition/src/main/java/com/iluwatar/spatialpartition/SpatialPartitionBubbles.java",
"spatial-partition/src/main/java/com/iluwatar/spatialpartition/SpatialPartitionGeneric.java"
] | [] | diff --git a/spatial-partition/src/main/java/com/iluwatar/spatialpartition/App.java b/spatial-partition/src/main/java/com/iluwatar/spatialpartition/App.java
index 47dcd7eb7560..e7b14249a732 100644
--- a/spatial-partition/src/main/java/com/iluwatar/spatialpartition/App.java
+++ b/spatial-partition/src/main/java/com/iluwatar/spatialpartition/App.java
@@ -25,7 +25,8 @@
package com.iluwatar.spatialpartition;
import java.security.SecureRandom;
-import java.util.HashMap;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
import lombok.extern.slf4j.Slf4j;
/**
@@ -59,9 +60,8 @@
@Slf4j
public class App {
- private static final String BUBBLE = "Bubble ";
- static void noSpatialPartition(int numOfMovements, HashMap<Integer, Bubble> bubbles) {
+ static void noSpatialPartition(int numOfMovements, Map<Integer, Bubble> bubbles) {
//all bubbles have to be checked for collision for all bubbles
var bubblesToCheck = bubbles.values();
@@ -77,11 +77,11 @@ static void noSpatialPartition(int numOfMovements, HashMap<Integer, Bubble> bubb
numOfMovements--;
}
//bubbles not popped
- bubbles.keySet().stream().map(key -> BUBBLE + key + " not popped").forEach(LOGGER::info);
+ bubbles.keySet().forEach(key -> LOGGER.info("Bubble {} not popped", key));
}
static void withSpatialPartition(
- int height, int width, int numOfMovements, HashMap<Integer, Bubble> bubbles) {
+ int height, int width, int numOfMovements, Map<Integer, Bubble> bubbles) {
//creating quadtree
var rect = new Rect(width / 2D, height / 2D, width, height);
var quadTree = new QuadTree(rect, 4);
@@ -100,7 +100,7 @@ static void withSpatialPartition(
numOfMovements--;
}
//bubbles not popped
- bubbles.keySet().stream().map(key -> BUBBLE + key + " not popped").forEach(LOGGER::info);
+ bubbles.keySet().forEach(key -> LOGGER.info("Bubble {} not popped", key));
}
/**
@@ -110,15 +110,15 @@ static void withSpatialPartition(
*/
public static void main(String[] args) {
- var bubbles1 = new HashMap<Integer, Bubble>();
- var bubbles2 = new HashMap<Integer, Bubble>();
+ var bubbles1 = new ConcurrentHashMap<Integer, Bubble>();
+ var bubbles2 = new ConcurrentHashMap<Integer, Bubble>();
var rand = new SecureRandom();
for (int i = 0; i < 10000; i++) {
var b = new Bubble(rand.nextInt(300), rand.nextInt(300), i, rand.nextInt(2) + 1);
bubbles1.put(i, b);
bubbles2.put(i, b);
- LOGGER.info(BUBBLE, i, " with radius ", b.radius,
- " added at (", b.coordinateX, ",", b.coordinateY + ")");
+ LOGGER.info("Bubble {} with radius {} added at ({},{})",
+ i, b.radius, b.coordinateX, b.coordinateY);
}
var start1 = System.currentTimeMillis();
@@ -127,8 +127,7 @@ public static void main(String[] args) {
var start2 = System.currentTimeMillis();
App.withSpatialPartition(300, 300, 20, bubbles2);
var end2 = System.currentTimeMillis();
- LOGGER.info("Without spatial partition takes ", (end1 - start1), "ms");
- LOGGER.info("With spatial partition takes ", (end2 - start2), "ms");
+ LOGGER.info("Without spatial partition takes {} ms", (end1 - start1));
+ LOGGER.info("With spatial partition takes {} ms", (end2 - start2));
}
}
-
diff --git a/spatial-partition/src/main/java/com/iluwatar/spatialpartition/Bubble.java b/spatial-partition/src/main/java/com/iluwatar/spatialpartition/Bubble.java
index f1f9fb61d03a..70f8cae48d65 100644
--- a/spatial-partition/src/main/java/com/iluwatar/spatialpartition/Bubble.java
+++ b/spatial-partition/src/main/java/com/iluwatar/spatialpartition/Bubble.java
@@ -26,7 +26,7 @@
import java.security.SecureRandom;
import java.util.Collection;
-import java.util.HashMap;
+import java.util.Map;
import lombok.extern.slf4j.Slf4j;
/**
@@ -58,13 +58,12 @@ boolean touches(Bubble b) {
<= (this.radius + b.radius) * (this.radius + b.radius);
}
- void pop(HashMap<Integer, Bubble> allBubbles) {
- LOGGER.info("Bubble ", this.id,
- " popped at (", this.coordinateX, ",", this.coordinateY, ")!");
+ void pop(Map<Integer, Bubble> allBubbles) {
+ LOGGER.info("Bubble {} popped at ({},{})!", this.id, this.coordinateX, this.coordinateY);
allBubbles.remove(this.id);
}
- void handleCollision(Collection<? extends Point> toCheck, HashMap<Integer, Bubble> allBubbles) {
+ void handleCollision(Collection<? extends Point> toCheck, Map<Integer, Bubble> allBubbles) {
var toBePopped = false; //if any other bubble collides with it, made true
for (var point : toCheck) {
var otherId = point.id;
diff --git a/spatial-partition/src/main/java/com/iluwatar/spatialpartition/Point.java b/spatial-partition/src/main/java/com/iluwatar/spatialpartition/Point.java
index 81312185247c..1b24e70fa37e 100644
--- a/spatial-partition/src/main/java/com/iluwatar/spatialpartition/Point.java
+++ b/spatial-partition/src/main/java/com/iluwatar/spatialpartition/Point.java
@@ -25,7 +25,7 @@
package com.iluwatar.spatialpartition;
import java.util.Collection;
-import java.util.HashMap;
+import java.util.Map;
/**
* The abstract Point class which will be extended by any object in the field whose location has to
@@ -65,5 +65,5 @@ public abstract class Point<T> {
* @param toCheck contains the objects which need to be checked
* @param all contains hashtable of all points on field at this time
*/
- abstract void handleCollision(Collection<? extends Point> toCheck, HashMap<Integer, T> all);
+ abstract void handleCollision(Collection<? extends Point> toCheck, Map<Integer, T> all);
}
diff --git a/spatial-partition/src/main/java/com/iluwatar/spatialpartition/QuadTree.java b/spatial-partition/src/main/java/com/iluwatar/spatialpartition/QuadTree.java
index 12a84f5a33e9..40c09a1d8f6e 100644
--- a/spatial-partition/src/main/java/com/iluwatar/spatialpartition/QuadTree.java
+++ b/spatial-partition/src/main/java/com/iluwatar/spatialpartition/QuadTree.java
@@ -25,7 +25,8 @@
package com.iluwatar.spatialpartition;
import java.util.Collection;
-import java.util.Hashtable;
+import java.util.HashMap;
+import java.util.Map;
/**
* The quadtree data structure is being used to keep track of the objects' locations. It has the
@@ -37,7 +38,7 @@ public class QuadTree {
Rect boundary;
int capacity;
boolean divided;
- Hashtable<Integer, Point> points;
+ Map<Integer, Point> points;
QuadTree northwest;
QuadTree northeast;
QuadTree southwest;
@@ -47,7 +48,7 @@ public class QuadTree {
this.boundary = boundary;
this.capacity = capacity;
this.divided = false;
- this.points = new Hashtable<>();
+ this.points = new HashMap<>();
this.northwest = null;
this.northeast = null;
this.southwest = null;
diff --git a/spatial-partition/src/main/java/com/iluwatar/spatialpartition/SpatialPartitionBubbles.java b/spatial-partition/src/main/java/com/iluwatar/spatialpartition/SpatialPartitionBubbles.java
index 50d20caa32f7..3551f5ca3b9b 100644
--- a/spatial-partition/src/main/java/com/iluwatar/spatialpartition/SpatialPartitionBubbles.java
+++ b/spatial-partition/src/main/java/com/iluwatar/spatialpartition/SpatialPartitionBubbles.java
@@ -25,7 +25,7 @@
package com.iluwatar.spatialpartition;
import java.util.ArrayList;
-import java.util.HashMap;
+import java.util.Map;
/**
* This class extends the generic SpatialPartition abstract class and is used in our example to keep
@@ -34,10 +34,10 @@
public class SpatialPartitionBubbles extends SpatialPartitionGeneric<Bubble> {
- private final HashMap<Integer, Bubble> bubbles;
+ private final Map<Integer, Bubble> bubbles;
private final QuadTree bubblesQuadTree;
- SpatialPartitionBubbles(HashMap<Integer, Bubble> bubbles, QuadTree bubblesQuadTree) {
+ SpatialPartitionBubbles(Map<Integer, Bubble> bubbles, QuadTree bubblesQuadTree) {
this.bubbles = bubbles;
this.bubblesQuadTree = bubblesQuadTree;
}
diff --git a/spatial-partition/src/main/java/com/iluwatar/spatialpartition/SpatialPartitionGeneric.java b/spatial-partition/src/main/java/com/iluwatar/spatialpartition/SpatialPartitionGeneric.java
index c1eb8d1f3600..7c03969a08e6 100644
--- a/spatial-partition/src/main/java/com/iluwatar/spatialpartition/SpatialPartitionGeneric.java
+++ b/spatial-partition/src/main/java/com/iluwatar/spatialpartition/SpatialPartitionGeneric.java
@@ -24,7 +24,7 @@
*/
package com.iluwatar.spatialpartition;
-import java.util.Hashtable;
+import java.util.Map;
/**
* This abstract class has 2 fields, one of which is a hashtable containing all objects that
@@ -35,7 +35,7 @@
public abstract class SpatialPartitionGeneric<T> {
- Hashtable<Integer, T> playerPositions;
+ Map<Integer, T> playerPositions;
QuadTree quadTree;
/**
| null | test | test | 2023-07-11T12:04:10 | "2023-06-27T15:18:54Z" | tiennm99 | train |
iluwatar/java-design-patterns/1306_2551 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/1306 | iluwatar/java-design-patterns/2551 | [
"timestamp(timedelta=134.0, similarity=0.8928222473875641)"
] | e40923d938cc94c096e1f3c19bc83b0caa85245a | 8b11e76f460667caf014e6731be9bc105031444d | [
"I would like to tackle this issue. ",
"Hey @iluwatar, I would like to help with this issue.",
"Thanks @MathewJaniec, please go ahead",
"This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.\n",
"@MathewJaniec, the pull request is still a draft and the build is failing.",
"This issue has been automatically marked as stale because it has not had recent activity. The issue will be unassigned if no further activity occurs. Thank you for your contributions.\n",
"Hi @iluwatar !\r\nCould I take this?",
"Please, it sounds like a really interesting topic @iluwatar 👉 👈 ",
"Closing this as completed. We have another related issue still open, see https://github.com/iluwatar/java-design-patterns/issues/1307"
] | [
"<picture><img alt=\"5% of developers fix this issue\" src=\"https://lift.sonatype.com/api/commentimage/fixrate/5/display.svg\"></picture>\n\n<b>*[UnnecessarilyFullyQualified](https://errorprone.info/bugpattern/UnnecessarilyFullyQualified):</b>* This fully qualified name is unambiguous to the compiler if imported.\n\n---\n\n\n```suggestion\n Generated\n```\n\n\n❗❗ <b>23 similar findings have been found in this PR</b>\n\n<details><summary>🔎 Expand here to view all instances of this finding</summary><br/>\n \n \n<div align=\\\"center\\\">\n\n\n| **File Path** | **Line Number** |\n| ------------- | ------------- |\n| optimistic-offline-lock/src/main/java/com/iluwatar/model/Card.java | [13](https://github.com/iluwatar/java-design-patterns/blob/cb541ab4d61d44e8ff6c5ac32a096da0fdabe60a/optimistic-offline-lock/src/main/java/com/iluwatar/model/Card.java#L13) |\n| optimistic-offline-lock/src/main/java/com/iluwatar/model/Card.java | [31](https://github.com/iluwatar/java-design-patterns/blob/cb541ab4d61d44e8ff6c5ac32a096da0fdabe60a/optimistic-offline-lock/src/main/java/com/iluwatar/model/Card.java#L31) |\n| optimistic-offline-lock/src/main/java/com/iluwatar/model/Card.java | [26](https://github.com/iluwatar/java-design-patterns/blob/cb541ab4d61d44e8ff6c5ac32a096da0fdabe60a/optimistic-offline-lock/src/main/java/com/iluwatar/model/Card.java#L26) |\n| optimistic-offline-lock/src/main/java/com/iluwatar/model/Card.java | [14](https://github.com/iluwatar/java-design-patterns/blob/cb541ab4d61d44e8ff6c5ac32a096da0fdabe60a/optimistic-offline-lock/src/main/java/com/iluwatar/model/Card.java#L14) |\n| optimistic-offline-lock/src/main/java/com/iluwatar/service/CardUpdateService.java | [12](https://github.com/iluwatar/java-design-patterns/blob/cb541ab4d61d44e8ff6c5ac32a096da0fdabe60a/optimistic-offline-lock/src/main/java/com/iluwatar/service/CardUpdateService.java#L12) |\n| optimistic-offline-lock/src/main/java/com/iluwatar/model/Card.java | [13](https://github.com/iluwatar/java-design-patterns/blob/cb541ab4d61d44e8ff6c5ac32a096da0fdabe60a/optimistic-offline-lock/src/main/java/com/iluwatar/model/Card.java#L13) |\n| optimistic-offline-lock/src/main/java/com/iluwatar/model/Card.java | [36](https://github.com/iluwatar/java-design-patterns/blob/cb541ab4d61d44e8ff6c5ac32a096da0fdabe60a/optimistic-offline-lock/src/main/java/com/iluwatar/model/Card.java#L36) |\n| optimistic-offline-lock/src/main/java/com/iluwatar/service/CardUpdateService.java | [12](https://github.com/iluwatar/java-design-patterns/blob/cb541ab4d61d44e8ff6c5ac32a096da0fdabe60a/optimistic-offline-lock/src/main/java/com/iluwatar/service/CardUpdateService.java#L12) |\n| optimistic-offline-lock/src/main/java/com/iluwatar/model/Card.java | [13](https://github.com/iluwatar/java-design-patterns/blob/cb541ab4d61d44e8ff6c5ac32a096da0fdabe60a/optimistic-offline-lock/src/main/java/com/iluwatar/model/Card.java#L13) |\n| optimistic-offline-lock/src/main/java/com/iluwatar/model/Card.java | [12](https://github.com/iluwatar/java-design-patterns/blob/cb541ab4d61d44e8ff6c5ac32a096da0fdabe60a/optimistic-offline-lock/src/main/java/com/iluwatar/model/Card.java#L12) |\n<p> Showing <b>10</b> of <b> 23 </b> findings. <a href=\"https://lift.sonatype.com/results/github.com/iluwatar/java-design-patterns/01H4WWW3Q3AY22WMCW38S4QPXX?t=ErrorProne|UnnecessarilyFullyQualified\" target=\"_blank\">Visit the Lift Web Console</a> to see all.</p></div></details>\n\n\n\n---\n\n<details><summary>ℹ️ Expand to see all <b>@sonatype-lift</b> commands</summary>\n\nYou can reply with the following commands. For example, reply with ***@sonatype-lift ignoreall*** to leave out all findings.\n| **Command** | **Usage** |\n| ------------- | ------------- |\n| `@sonatype-lift ignore` | Leave out the above finding from this PR |\n| `@sonatype-lift ignoreall` | Leave out all the existing findings from this PR |\n| `@sonatype-lift exclude <file\\|issue\\|path\\|tool>` | Exclude specified `file\\|issue\\|path\\|tool` from Lift findings by updating your config.toml file |\n\n**Note:** When talking to LiftBot, you need to **refresh** the page to see its response.\n<sub>[Click here](https://github.com/apps/sonatype-lift/installations/new) to add LiftBot to another repo.</sub></details>\n\n"
] | "2023-07-08T19:46:23Z" | [
"epic: pattern",
"type: feature"
] | Optimistic Offline Lock pattern | https://books.google.fi/books?id=vqTfNFDzzdIC&pg=PA416#v=onepage&q&f=false | [
"pom.xml"
] | [
"optimistic-offline-lock/README.md",
"optimistic-offline-lock/pom.xml",
"optimistic-offline-lock/src/main/java/com/iluwatar/api/UpdateService.java",
"optimistic-offline-lock/src/main/java/com/iluwatar/exception/ApplicationException.java",
"optimistic-offline-lock/src/main/java/com/iluwatar/model/Card.java",
"optimistic-offline-lock/src/main/java/com/iluwatar/repository/JpaRepository.java",
"optimistic-offline-lock/src/main/java/com/iluwatar/service/CardUpdateService.java",
"pom.xml"
] | [
"optimistic-offline-lock/src/test/java/com/iluwatar/OptimisticLockTest.java"
] | diff --git a/optimistic-offline-lock/README.md b/optimistic-offline-lock/README.md
new file mode 100644
index 000000000000..7447a30503c7
--- /dev/null
+++ b/optimistic-offline-lock/README.md
@@ -0,0 +1,147 @@
+---
+title: Optimistic Offline Lock
+category: Concurrency
+language: en
+tag:
+- Data access
+---
+
+## Intent
+
+Provide an ability to avoid concurrent changes of one record in relational databases.
+
+## Explanation
+
+Each transaction during object modifying checks equation of object's version before start of transaction
+and before commit itself.
+
+**Real world example**
+> Since people love money, the best (and most common) example is banking system:
+> imagine you have 100$ on your e-wallet and two people are trying to send you 50$ both at a time.
+> Without locking, your system will start **two different thread**, each of whose will read your current balance
+> and just add 50$. The last thread won't re-read balance and will just rewrite it.
+> So, instead 200$ you will have only 150$.
+
+**In plain words**
+> Each transaction during object modifying will save object's last version and check it before saving.
+> If it differs, the transaction will be rolled back.
+
+**Wikipedia says**
+> Optimistic concurrency control (OCC), also known as optimistic locking,
+> is a concurrency control method applied to transactional systems such as
+> relational database management systems and software transactional memory.
+
+**Programmatic Example**
+Let's simulate the case from *real world example*. Imagine we have next entity:
+
+```java
+import lombok.AllArgsConstructor;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+
+/**
+ * Bank card entity.
+ */
+@Data
+@NoArgsConstructor
+@AllArgsConstructor
+public class Card {
+
+ /**
+ * Primary key.
+ */
+ private long id;
+
+ /**
+ * Foreign key points to card's owner.
+ */
+ private long personId;
+
+ /**
+ * Sum of money.
+ */
+ private float sum;
+
+ /**
+ * Current version of object;
+ */
+ private int version;
+}
+```
+
+Then the correct modifying will be like this:
+
+```java
+
+import lombok.RequiredArgsConstructor;
+
+/**
+ * Service to update {@link Card} entity.
+ */
+@RequiredArgsConstructor
+public class CardUpdateService implements UpdateService<Card> {
+
+ private final JpaRepository<Card> cardJpaRepository;
+
+ @Override
+ @Transactional(rollbackFor = ApplicationException.class) //will roll back transaction in case ApplicationException
+ public Card doUpdate(Card card, long cardId) {
+ float additionalSum = card.getSum();
+ Card cardToUpdate = cardJpaRepository.findById(cardId);
+ int initialVersion = cardToUpdate.getVersion();
+ float resultSum = cardToUpdate.getSum() + additionalSum;
+ cardToUpdate.setSum(resultSum);
+ //Maybe more complex business-logic e.g. HTTP-requests and so on
+
+ if (initialVersion != cardJpaRepository.getEntityVersionById(cardId)) {
+ String exMessage = String.format("Entity with id %s were updated in another transaction", cardId);
+ throw new ApplicationException(exMessage);
+ }
+
+ cardJpaRepository.update(cardToUpdate);
+ return cardToUpdate;
+ }
+}
+```
+
+## Applicability
+
+Since optimistic locking can cause degradation of system's efficiency and reliability due to
+many retries/rollbacks, it's important to use it safely. They are useful in case when transactions are not so long
+and does not distributed among many microservices, when you need to reduce network/database overhead.
+
+Important to note that you should not choose this approach in case when modifying one object
+in different threads is common situation.
+
+## Tutorials
+
+- [Offline Concurrency Control](https://www.baeldung.com/cs/offline-concurrency-control)
+- [Optimistic lock in JPA](https://www.baeldung.com/jpa-optimistic-locking)
+
+## Known uses
+
+- [Hibernate ORM](https://docs.jboss.org/hibernate/orm/4.3/devguide/en-US/html/ch05.html)
+
+## Consequences
+
+**Advantages**:
+
+- Reduces network/database overhead
+- Let to avoid database deadlock
+- Improve the performance and scalability of the application
+
+**Disadvantages**:
+
+- Increases complexity of the application
+- Requires mechanism of versioning
+- Requires rollback/retry mechanisms
+
+## Related patterns
+
+- [Pessimistic Offline Lock](https://martinfowler.com/eaaCatalog/pessimisticOfflineLock.html)
+
+## Credits
+
+- [Source (Martin Fowler)](https://martinfowler.com/eaaCatalog/optimisticOfflineLock.html)
+- [Advantages and disadvantages](https://www.linkedin.com/advice/0/what-benefits-drawbacks-using-optimistic)
+- [Comparison of optimistic and pessimistic locks](https://www.linkedin.com/advice/0/what-advantages-disadvantages-using-optimistic)
\ No newline at end of file
diff --git a/optimistic-offline-lock/pom.xml b/optimistic-offline-lock/pom.xml
new file mode 100644
index 000000000000..d32c46df4534
--- /dev/null
+++ b/optimistic-offline-lock/pom.xml
@@ -0,0 +1,52 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+
+ This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
+
+ The MIT License
+ Copyright © 2014-2022 Ilkka Seppälä
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+
+ <parent>
+ <groupId>com.iluwatar</groupId>
+ <artifactId>java-design-patterns</artifactId>
+ <version>1.26.0-SNAPSHOT</version>
+ </parent>
+
+ <artifactId>optimistic-offline-lock</artifactId>
+
+ <dependencies>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-engine</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.mockito</groupId>
+ <artifactId>mockito-core</artifactId>
+ <scope>test</scope>
+ </dependency>
+ </dependencies>
+</project>
diff --git a/optimistic-offline-lock/src/main/java/com/iluwatar/api/UpdateService.java b/optimistic-offline-lock/src/main/java/com/iluwatar/api/UpdateService.java
new file mode 100644
index 000000000000..b3c29d22f0b9
--- /dev/null
+++ b/optimistic-offline-lock/src/main/java/com/iluwatar/api/UpdateService.java
@@ -0,0 +1,18 @@
+package com.iluwatar.api;
+
+/**
+ * Service for entity update.
+ *
+ * @param <T> target entity
+ */
+public interface UpdateService<T> {
+
+ /**
+ * Update entity.
+ *
+ * @param obj entity to update
+ * @param id primary key
+ * @return modified entity
+ */
+ T doUpdate(T obj, long id);
+}
diff --git a/optimistic-offline-lock/src/main/java/com/iluwatar/exception/ApplicationException.java b/optimistic-offline-lock/src/main/java/com/iluwatar/exception/ApplicationException.java
new file mode 100644
index 000000000000..7d12c3350e8b
--- /dev/null
+++ b/optimistic-offline-lock/src/main/java/com/iluwatar/exception/ApplicationException.java
@@ -0,0 +1,16 @@
+package com.iluwatar.exception;
+
+/**
+ * Exception happens in application during business-logic execution.
+ */
+public class ApplicationException extends RuntimeException {
+
+ /**
+ * Inherited constructor with exception message.
+ *
+ * @param message exception message
+ */
+ public ApplicationException(String message) {
+ super(message);
+ }
+}
diff --git a/optimistic-offline-lock/src/main/java/com/iluwatar/model/Card.java b/optimistic-offline-lock/src/main/java/com/iluwatar/model/Card.java
new file mode 100644
index 000000000000..b36c779d6ba4
--- /dev/null
+++ b/optimistic-offline-lock/src/main/java/com/iluwatar/model/Card.java
@@ -0,0 +1,37 @@
+package com.iluwatar.model;
+
+
+import lombok.AllArgsConstructor;
+import lombok.Builder;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+
+/**
+ * Bank card entity.
+ */
+@Data
+@Builder
+@NoArgsConstructor
+@AllArgsConstructor
+public class Card {
+
+ /**
+ * Primary key.
+ */
+ private long id;
+
+ /**
+ * Foreign key points to card's owner.
+ */
+ private long personId;
+
+ /**
+ * Sum of money.
+ */
+ private float sum;
+
+ /**
+ * Current version of object.
+ */
+ private int version;
+}
diff --git a/optimistic-offline-lock/src/main/java/com/iluwatar/repository/JpaRepository.java b/optimistic-offline-lock/src/main/java/com/iluwatar/repository/JpaRepository.java
new file mode 100644
index 000000000000..b1d3c240a0ce
--- /dev/null
+++ b/optimistic-offline-lock/src/main/java/com/iluwatar/repository/JpaRepository.java
@@ -0,0 +1,33 @@
+package com.iluwatar.repository;
+
+/**
+ * Imitation of Spring's JpaRepository.
+ *
+ * @param <T> target database entity
+ */
+public interface JpaRepository<T> {
+
+ /**
+ * Get object by it's PK.
+ *
+ * @param id primary key
+ * @return {@link T}
+ */
+ T findById(long id);
+
+ /**
+ * Get current object version.
+ *
+ * @param id primary key
+ * @return object's version
+ */
+ int getEntityVersionById(long id);
+
+ /**
+ * Update object.
+ *
+ * @param obj entity to update
+ * @return number of modified records
+ */
+ int update(T obj);
+}
diff --git a/optimistic-offline-lock/src/main/java/com/iluwatar/service/CardUpdateService.java b/optimistic-offline-lock/src/main/java/com/iluwatar/service/CardUpdateService.java
new file mode 100644
index 000000000000..0f67c1e5e85f
--- /dev/null
+++ b/optimistic-offline-lock/src/main/java/com/iluwatar/service/CardUpdateService.java
@@ -0,0 +1,35 @@
+package com.iluwatar.service;
+
+import com.iluwatar.api.UpdateService;
+import com.iluwatar.exception.ApplicationException;
+import com.iluwatar.model.Card;
+import com.iluwatar.repository.JpaRepository;
+import lombok.RequiredArgsConstructor;
+
+/**
+ * Service to update {@link Card} entity.
+ */
+@RequiredArgsConstructor
+public class CardUpdateService implements UpdateService<Card> {
+
+ private final JpaRepository<Card> cardJpaRepository;
+
+ @Override
+ public Card doUpdate(Card obj, long id) {
+ float additionalSum = obj.getSum();
+ Card cardToUpdate = cardJpaRepository.findById(id);
+ int initialVersion = cardToUpdate.getVersion();
+ float resultSum = cardToUpdate.getSum() + additionalSum;
+ cardToUpdate.setSum(resultSum);
+ //Maybe more complex business-logic e.g. HTTP-requests and so on
+
+ if (initialVersion != cardJpaRepository.getEntityVersionById(id)) {
+ String exMessage =
+ String.format("Entity with id %s were updated in another transaction", id);
+ throw new ApplicationException(exMessage);
+ }
+
+ cardJpaRepository.update(cardToUpdate);
+ return cardToUpdate;
+ }
+}
diff --git a/pom.xml b/pom.xml
index 10348ef0466a..9e46d17f9cfc 100644
--- a/pom.xml
+++ b/pom.xml
@@ -206,6 +206,7 @@
<module>component</module>
<module>context-object</module>
<module>thread-local-storage</module>
+ <module>optimistic-offline-lock</module>
</modules>
<repositories>
<repository>
| diff --git a/optimistic-offline-lock/src/test/java/com/iluwatar/OptimisticLockTest.java b/optimistic-offline-lock/src/test/java/com/iluwatar/OptimisticLockTest.java
new file mode 100644
index 000000000000..479b5807838e
--- /dev/null
+++ b/optimistic-offline-lock/src/test/java/com/iluwatar/OptimisticLockTest.java
@@ -0,0 +1,60 @@
+package com.iluwatar;
+
+import com.iluwatar.exception.ApplicationException;
+import com.iluwatar.model.Card;
+import com.iluwatar.repository.JpaRepository;
+import com.iluwatar.service.CardUpdateService;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mockito;
+
+import static org.mockito.Mockito.when;
+import static org.mockito.Mockito.eq;
+
+@SuppressWarnings({"rawtypes", "unchecked"})
+public class OptimisticLockTest {
+
+ private CardUpdateService cardUpdateService;
+
+ private JpaRepository cardRepository;
+
+ @BeforeEach
+ public void setUp() {
+ cardRepository = Mockito.mock(JpaRepository.class);
+ cardUpdateService = new CardUpdateService(cardRepository);
+ }
+
+ @Test
+ public void shouldNotUpdateEntityOnDifferentVersion() {
+ int initialVersion = 1;
+ long cardId = 123L;
+ Card card = Card.builder()
+ .id(cardId)
+ .version(initialVersion)
+ .sum(123f)
+ .build();
+ when(cardRepository.findById(eq(cardId))).thenReturn(card);
+ when(cardRepository.getEntityVersionById(Mockito.eq(cardId))).thenReturn(initialVersion + 1);
+
+ Assertions.assertThrows(ApplicationException.class,
+ () -> cardUpdateService.doUpdate(card, cardId));
+ }
+
+ @Test
+ public void shouldUpdateOnSameVersion() {
+ int initialVersion = 1;
+ long cardId = 123L;
+ Card card = Card.builder()
+ .id(cardId)
+ .version(initialVersion)
+ .sum(123f)
+ .build();
+ when(cardRepository.findById(eq(cardId))).thenReturn(card);
+ when(cardRepository.getEntityVersionById(Mockito.eq(cardId))).thenReturn(initialVersion);
+
+ cardUpdateService.doUpdate(card, cardId);
+
+ Mockito.verify(cardRepository).update(Mockito.any());
+ }
+}
| test | test | 2023-07-04T17:23:11 | "2020-07-07T17:51:56Z" | iluwatar | train |
iluwatar/java-design-patterns/2241_2583 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/2241 | iluwatar/java-design-patterns/2583 | [
"timestamp(timedelta=61.0, similarity=0.9398683357371884)"
] | cb2d794cf85ed7bb4c251decf36fef0e0655d820 | ae597f259622c3f6c646cf0099fd103089aa1327 | [
"hi @iluwatar , can I take this up? Thanks",
"hi @iluwatar , have opened this PR: https://github.com/iluwatar/java-design-patterns/pull/2583\r\nThanks"
] | [] | "2023-09-09T04:28:09Z" | [
"type: feature",
"epic: documentation"
] | Explanation for Master-Worker | In this issue, let's add a proper explanation for the pattern.
Acceptance criteria
- The pattern's README.md has been amended with an explanation
- The explanation consists of
- Real world example
- In plain words
- Wikipedia says
- Programmatic example
| [
"master-worker-pattern/README.md"
] | [
"master-worker-pattern/README.md"
] | [] | diff --git a/master-worker-pattern/README.md b/master-worker-pattern/README.md
index fc4e111ae412..32f239078517 100644
--- a/master-worker-pattern/README.md
+++ b/master-worker-pattern/README.md
@@ -17,6 +17,83 @@ tag:
## Class diagram
![alt text](./etc/master-worker-pattern.urm.png "Master-Worker pattern class diagram")
+## Explanation
+
+Real World Example
+>Imagine you have a large stack of papers to grade as a teacher. You decide to hire several teaching assistants to help you. You, as the "master," distribute different papers to each teaching assistant, they grade them independently, and return the graded papers to you. Finally, you collect all the graded papers, review them, and calculate the final grades. This process of dividing work among assistants, parallel processing, and aggregating results is similar to the Master-Worker pattern.
+
+In Plain Words
+>The Master-Worker pattern is like a boss (the master) assigning tasks to workers and then combining the results. It's a way to efficiently break down a big job into smaller pieces that can be done concurrently.
+
+Wikipedia Says
+>According to [Wikipedia](https://en.wikipedia.org/wiki/Master/slave_(technology)), the Master-Worker pattern, also known as Master-Slave or Map-Reduce, is a design pattern used in software engineering for parallel processing. In this pattern, a "master" component divides a complex task into smaller subtasks and assigns them to multiple "worker" components. Each worker processes its assigned subtask independently, and the master collects and combines the results to produce the final output.
+
+Programmatic Example
+
+```java
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.*;
+
+// Define a task that workers (teaching assistants) will perform
+class GradingWorkerTask implements Callable<Integer> {
+ private int paperNumber;
+
+ public GradingWorkerTask(int paperNumber) {
+ this.paperNumber = paperNumber;
+ }
+
+ @Override
+ public Integer call() throws Exception {
+ // Simulate grading a paper (e.g., assigning a score)
+ int score = (int) (Math.random() * 100); // Assign a random score
+ // Simulate some grading time
+ Thread.sleep((int) (Math.random() * 1000));
+ System.out.println("Graded paper #" + paperNumber + " with a score of " + score);
+ return score;
+ }
+}
+```
+
+```java
+public class PaperGrading {
+ public static void main(String[] args) {
+ int totalPapersToGrade = 20; // Total number of papers to grade
+ int numberOfTeachingAssistants = 3; // Number of teaching assistants
+
+ // Create a thread pool with a fixed number of teaching assistants (workers)
+ ExecutorService executor = Executors.newFixedThreadPool(numberOfTeachingAssistants);
+
+ // Create and submit grading tasks to the executor for each paper
+ List<Future<Integer>> results = new ArrayList<>();
+ for (int paperNumber = 1; paperNumber <= totalPapersToGrade; paperNumber++) {
+ results.add(executor.submit(new GradingWorkerTask(paperNumber)));
+ }
+
+ // Shutdown the executor to prevent new tasks from being submitted
+ executor.shutdown();
+
+ // Collect and analyze the grading results
+ int totalScore = 0;
+ for (Future<Integer> result : results) {
+ try {
+ // Get the score of each graded paper and calculate the total score
+ totalScore += result.get();
+ } catch (InterruptedException | ExecutionException e) {
+ e.printStackTrace();
+ }
+ }
+
+ double averageScore = (double) totalScore / totalPapersToGrade;
+
+ System.out.println("Grading completed.");
+ System.out.println("Total papers graded: " + totalPapersToGrade);
+ System.out.println("Total score: " + totalScore);
+ System.out.println("Average score: " + averageScore);
+ }
+}
+```
+
## Applicability
This pattern can be used when data can be divided into multiple parts, all of which need to go through the same computation to give a result, which need to be aggregated to get the final result.
| null | train | test | 2023-08-27T13:40:17 | "2022-10-29T19:59:47Z" | iluwatar | train |
iluwatar/java-design-patterns/2260_2586 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/2260 | iluwatar/java-design-patterns/2586 | [
"keyword_pr_to_issue"
] | cb2d794cf85ed7bb4c251decf36fef0e0655d820 | 9561722bb5770d82d781536b359b65595791e4d7 | [
"Hello. I want to nominate myself for writing explanation about Servant design pattern.",
"Hi @iluwatar, I would like to take care of the above feature. Please assign it to me."
] | [] | "2023-09-15T12:21:26Z" | [
"type: feature",
"epic: documentation"
] | Explanation for Servant | In this issue, let's add a proper explanation for the pattern.
Acceptance criteria
- The pattern's README.md has been amended with an explanation
- The explanation consists of
- Real world example
- In plain words
- Wikipedia says
- Programmatic example
| [
"servant/README.md"
] | [
"servant/README.md"
] | [] | diff --git a/servant/README.md b/servant/README.md
index bfd06e2bc37a..c6aaf414873d 100644
--- a/servant/README.md
+++ b/servant/README.md
@@ -3,7 +3,7 @@ title: Servant
category: Behavioral
language: en
tag:
- - Decoupling
+- Decoupling
---
## Intent
@@ -11,6 +11,217 @@ Servant is used for providing some behavior to a group of classes.
Instead of defining that behavior in each class - or when we cannot factor out
this behavior in the common parent class - it is defined once in the Servant.
+## Explanation
+
+Real-world example
+
+> King, Queen, and other royal member of palace need servant to service them for feeding,
+> organizing drinks, and so on.
+
+In plain words
+
+> Ensures one servant object to give some specific services for a group of serviced classes.
+
+Wikipedia says
+
+> In software engineering, the servant pattern defines an object used to offer some functionality
+> to a group of classes without defining that functionality in each of them. A Servant is a class
+> whose instance (or even just class) provides methods that take care of a desired service, while
+> objects for which (or with whom) the servant does something, are taken as parameters.
+
+**Programmatic Example**
+
+Servant class which can give services to other royal members of palace.
+
+```java
+/**
+ * Servant.
+ */
+public class Servant {
+
+ public String name;
+
+ /**
+ * Constructor.
+ */
+ public Servant(String name) {
+ this.name = name;
+ }
+
+ public void feed(Royalty r) {
+ r.getFed();
+ }
+
+ public void giveWine(Royalty r) {
+ r.getDrink();
+ }
+
+ public void giveCompliments(Royalty r) {
+ r.receiveCompliments();
+ }
+
+ /**
+ * Check if we will be hanged.
+ */
+ public boolean checkIfYouWillBeHanged(List<Royalty> tableGuests) {
+ return tableGuests.stream().allMatch(Royalty::getMood);
+ }
+}
+```
+
+Royalty is an interface. It is implemented by King, and Queen classes to get services from servant.
+
+```java
+interface Royalty {
+
+ void getFed();
+
+ void getDrink();
+
+ void changeMood();
+
+ void receiveCompliments();
+
+ boolean getMood();
+}
+```
+King, class is implementing Royalty interface.
+```java
+public class King implements Royalty {
+
+ private boolean isDrunk;
+ private boolean isHungry = true;
+ private boolean isHappy;
+ private boolean complimentReceived;
+
+ @Override
+ public void getFed() {
+ isHungry = false;
+ }
+
+ @Override
+ public void getDrink() {
+ isDrunk = true;
+ }
+
+ public void receiveCompliments() {
+ complimentReceived = true;
+ }
+
+ @Override
+ public void changeMood() {
+ if (!isHungry && isDrunk) {
+ isHappy = true;
+ }
+ if (complimentReceived) {
+ isHappy = false;
+ }
+ }
+
+ @Override
+ public boolean getMood() {
+ return isHappy;
+ }
+}
+```
+Queen, class is implementing Royalty interface.
+```java
+public class Queen implements Royalty {
+
+ private boolean isDrunk = true;
+ private boolean isHungry;
+ private boolean isHappy;
+ private boolean isFlirty = true;
+ private boolean complimentReceived;
+
+ @Override
+ public void getFed() {
+ isHungry = false;
+ }
+
+ @Override
+ public void getDrink() {
+ isDrunk = true;
+ }
+
+ public void receiveCompliments() {
+ complimentReceived = true;
+ }
+
+ @Override
+ public void changeMood() {
+ if (complimentReceived && isFlirty && isDrunk && !isHungry) {
+ isHappy = true;
+ }
+ }
+
+ @Override
+ public boolean getMood() {
+ return isHappy;
+ }
+
+ public void setFlirtiness(boolean f) {
+ this.isFlirty = f;
+ }
+
+}
+```
+
+Then in order to use:
+
+```java
+public class App {
+
+ private static final Servant jenkins = new Servant("Jenkins");
+ private static final Servant travis = new Servant("Travis");
+
+ /**
+ * Program entry point.
+ */
+ public static void main(String[] args) {
+ scenario(jenkins, 1);
+ scenario(travis, 0);
+ }
+
+ /**
+ * Can add a List with enum Actions for variable scenarios.
+ */
+ public static void scenario(Servant servant, int compliment) {
+ var k = new King();
+ var q = new Queen();
+
+ var guests = List.of(k, q);
+
+ // feed
+ servant.feed(k);
+ servant.feed(q);
+ // serve drinks
+ servant.giveWine(k);
+ servant.giveWine(q);
+ // compliment
+ servant.giveCompliments(guests.get(compliment));
+
+ // outcome of the night
+ guests.forEach(Royalty::changeMood);
+
+ // check your luck
+ if (servant.checkIfYouWillBeHanged(guests)) {
+ LOGGER.info("{} will live another day", servant.name);
+ } else {
+ LOGGER.info("Poor {}. His days are numbered", servant.name);
+ }
+ }
+}
+```
+
+The console output
+
+```
+Jenkins will live another day
+Poor Travis. His days are numbered
+```
+
+
## Class diagram
![alt text](./etc/servant-pattern.png "Servant")
| null | train | test | 2023-08-27T13:40:17 | "2022-10-29T20:04:48Z" | iluwatar | train |
iluwatar/java-design-patterns/2266_2596 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/2266 | iluwatar/java-design-patterns/2596 | [
"keyword_pr_to_issue"
] | cb2d794cf85ed7bb4c251decf36fef0e0655d820 | ffbcbdcb33bcd739fbfb58b70faab5cc26a44954 | [] | [] | "2023-10-02T12:56:07Z" | [
"info: help wanted",
"type: feature",
"epic: documentation"
] | Explanation for Type-Object | In this issue, let's add a proper explanation for the pattern.
Acceptance criteria
- The pattern's README.md has been amended with an explanation
- The explanation consists of
- Real world example
- In plain words
- Wikipedia says
- Programmatic example
| [
"typeobjectpattern/README.md"
] | [
"typeobjectpattern/README.md"
] | [] | diff --git a/typeobjectpattern/README.md b/typeobjectpattern/README.md
index f75e217d2616..742792a8f423 100644
--- a/typeobjectpattern/README.md
+++ b/typeobjectpattern/README.md
@@ -7,17 +7,63 @@ tag:
- Extensibility
---
+# Type-Object Pattern in Java
+
+## Explanation
+
+In Java, the Type-Object pattern is a design pattern that encapsulates type information in an object. This pattern is particularly useful when dealing with multiple objects of the same kind, and there is a need to add new types without altering existing code.
+
## Intent
As explained in the book Game Programming Patterns by Robert Nystrom, type object pattern helps in
> Allowing flexible creation of new “classes” by creating a single class, each instance of which represents a different type of object
-## Explanation
-Say, we are working on a game which has a hero and many monsters which are going to attack the hero. These monsters have certain attributes like attack, points etc. and come in different 'breeds' like zombie or ogres. The obvious answer is to have a base Monster class which has some fields and methods, which may be overriden by subclasses like the Zombie or Ogre class. But as we continue to build the game, there may be more and more breeds of monsters added and certain attributes may need to be changed in the existing monsters too. The OOP solution of inheriting from the base class would not be an efficient method in this case.
+## Real World Example
+Let's consider a real-world example. Say, we are working on a game which has a hero and many monsters which are going to attack the hero. These monsters have certain attributes like attack, points etc. and come in different 'breeds' like zombie or ogres. The obvious answer is to have a base Monster class which has some fields and methods, which may be overriden by subclasses like the Zombie or Ogre class. But as we continue to build the game, there may be more and more breeds of monsters added and certain attributes may need to be changed in the existing monsters too. The OOP solution of inheriting from the base class would not be an efficient method in this case.
Using the type-object pattern, instead of creating many classes inheriting from a base class, we have 1 class with a field which represents the 'type' of object. This makes the code cleaner and object instantiation also becomes as easy as parsing a json file with the object properties.
-## Class diagram
-![alt text](./etc/typeobjectpattern.urm.png "Type-Object pattern class diagram")
+## In Plain Words
+
+The Type-Object pattern in Java is a method to encapsulate type-specific properties and behaviors within an object. This design pattern facilitates the addition of new types without necessitating changes to existing code, thereby enhancing codebase expansion and maintenance.
+
+## Wikipedia Says
+
+While there isn't a specific Wikipedia entry for the Type-Object pattern, it is a commonly used technique in object-oriented programming. This pattern assists in managing objects that share similar characteristics but have different values for those characteristics. It finds widespread use in game development, where numerous types of objects (like enemies) share common behavior but have different properties.
+
+## Programmatic Example
+
+Consider an example involving different types of enemies in a game. Each enemy type has distinct properties like speed, health, and damage.
+
+```java
+public class EnemyType {
+ private String name;
+ private int speed;
+ private int health;
+ private int damage;
+
+ public EnemyType(String name, int speed, int health, int damage) {
+ this.name = name;
+ this.speed = speed;
+ this.health = health;
+ this.damage = damage;
+ }
+
+ // getters and setters
+}
+
+public class Enemy {
+ private EnemyType type;
+
+ // Encapsulating type information in an object
+ public Enemy(EnemyType type) {
+ this.type = type;
+ }
+
+ // other methods
+}
+```
+
+In the above example, `EnemyType` encapsulates type-specific properties (name, speed, health, damage), and `Enemy` uses an instance of `EnemyType` to define its type. This way, you can add as many enemy types as you want without modifying the `Enemy` class.
## Applicability
This pattern can be used when:
@@ -25,7 +71,10 @@ This pattern can be used when:
* We don’t know what types we will need up front.
* We want to be able to modify or add new types without having to recompile or change code.
* Only difference between the different 'types' of objects is the data, not the behaviour.
-
+
+## Another example with class diagram
+![alt text](./etc/typeobjectpattern.urm.png "Type-Object pattern class diagram")
+
## Credits
* [Game Programming Patterns - Type Object](http://gameprogrammingpatterns.com/type-object.html)
| null | test | test | 2023-08-27T13:40:17 | "2022-10-29T20:05:06Z" | iluwatar | train |
iluwatar/java-design-patterns/2250_2597 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/2250 | iluwatar/java-design-patterns/2597 | [
"timestamp(timedelta=1.0, similarity=0.8431716746288775)",
"keyword_pr_to_issue"
] | cb2d794cf85ed7bb4c251decf36fef0e0655d820 | b75c7c1041aa56a837a35b6c41b04a5d9680a6e4 | [
"Hey @iluwatar I can work on this. "
] | [] | "2023-10-02T13:35:33Z" | [
"type: feature",
"epic: documentation"
] | Explanation for Page Object | In this issue, let's add a proper explanation for the pattern.
Acceptance criteria
- The pattern's README.md has been amended with an explanation
- The explanation consists of
- Real world example
- In plain words
- Wikipedia says
- Programmatic example
| [
"page-object/README.md"
] | [
"page-object/README.md"
] | [] | diff --git a/page-object/README.md b/page-object/README.md
index 87046a85d917..93777ad2e032 100644
--- a/page-object/README.md
+++ b/page-object/README.md
@@ -6,13 +6,69 @@ tag:
- Decoupling
---
+# Page Object Pattern in Java
+
+## Real World Example
+
+Consider a web automation scenario where you need to interact with a web page using a test framework like Selenium. The Page Object pattern can be applied to model each web page as a Java class. Each class encapsulates the structure and behavior of the corresponding web page, making it easier to manage and update the automation code.
+
## Intent
Page Object encapsulates the UI, hiding the underlying UI widgetry of an application (commonly a web application) and providing an application-specific API to allow the manipulation of UI components required for tests. In doing so, it allows the test class itself to focus on the test logic instead.
-## Class diagram
-![alt text](./etc/page-object.png "Page Object")
+## In Plain Words
+
+The Page Object pattern in Java is a design pattern used in test automation to represent web pages as Java classes. Each class corresponds to a specific web page and contains methods to interact with the elements on that page. This pattern enhances code maintainability and readability in automated testing.
+
+## Wikipedia Says
+
+While there isn't a specific Wikipedia entry for the Page Object pattern, it is widely used in software testing, particularly in the context of UI automation. The Page Object pattern helps abstract the details of a web page, providing a cleaner and more maintainable way to interact with web elements in automated tests.
+
+## Programmatic Example
+
+Let's create a simple programmatic example of the Page Object pattern for a login page using Selenium in Java:
+
+```java
+import org.openqa.selenium.By;
+import org.openqa.selenium.WebDriver;
+import org.openqa.selenium.WebElement;
+
+public class LoginPage {
+ private final WebDriver driver;
+ // Web elements on the login page
+ private final By usernameInput = By.id("username");
+ private final By passwordInput = By.id("password");
+ private final By loginButton = By.id("login-button");
+
+ public LoginPage(WebDriver driver) {
+ this.driver = driver;
+ }
+
+ // Methods to interact with the login page
+
+ public void enterUsername(String username) {
+ WebElement usernameElement = driver.findElement(usernameInput);
+ usernameElement.sendKeys(username);
+ }
+
+ public void enterPassword(String password) {
+ WebElement passwordElement = driver.findElement(passwordInput);
+ passwordElement.sendKeys(password);
+ }
+
+ public void clickLoginButton() {
+ WebElement loginButtonElement = driver.findElement(loginButton);
+ loginButtonElement.click();
+ }
+
+ // Other methods specific to the login page if needed
+}
+```
+
+In this example, the `LoginPage` class represents the login page of a web application. It encapsulates the web elements on the page and provides methods to interact with those elements. The actual Selenium WebDriver instance is passed to the constructor, allowing the methods to perform actions on the web page.
+
+This Page Object can be used in test scripts to interact with the login page without exposing the details of the page structure in the test code, promoting maintainability and reusability.
## Applicability
@@ -21,6 +77,9 @@ Use the Page Object pattern when
* You are writing automated tests for your web application and you want to separate the UI manipulation required for the tests from the actual test logic.
* Make your tests less brittle, and more readable and robust
+## Another example with Class diagram
+![alt text](./etc/page-object.png "Page Object")
+
## Credits
* [Martin Fowler - PageObject](http://martinfowler.com/bliki/PageObject.html)
| null | train | test | 2023-08-27T13:40:17 | "2022-10-29T20:00:13Z" | iluwatar | train |
iluwatar/java-design-patterns/2263_2614 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/2263 | iluwatar/java-design-patterns/2614 | [
"keyword_pr_to_issue"
] | cb2d794cf85ed7bb4c251decf36fef0e0655d820 | b71eea4b4e4849e593b8d7e23bb0cbbb6404955c | [
"can you assign it to me?",
"This issue has been automatically marked as stale because it has not had recent activity. The issue will be unassigned if no further activity occurs. Thank you for your contributions.\n",
"Please assign this to me.\r\n"
] | [] | "2023-10-05T12:07:29Z" | [
"type: feature",
"epic: documentation"
] | Explanation for Step Builder | In this issue, let's add a proper explanation for the pattern.
Acceptance criteria
- The pattern's README.md has been amended with an explanation
- The explanation consists of
- Real world example
- In plain words
- Wikipedia says
- Programmatic example
| [
"step-builder/README.md"
] | [
"step-builder/README.md"
] | [] | diff --git a/step-builder/README.md b/step-builder/README.md
index 659da6e31968..a1e98b237611 100644
--- a/step-builder/README.md
+++ b/step-builder/README.md
@@ -6,16 +6,100 @@ tag:
- Instantiation
---
+# Step Builder Pattern
+
+## Explanation
+
+The Step Builder pattern is a creational design pattern used to construct a complex object step by step. It provides a fluent interface to create an object with a large number of possible configurations, making the code more readable and reducing the need for multiple constructors or setter methods.
+
## Intent
An extension of the Builder pattern that fully guides the user through the creation of the object with no chances of confusion.
The user experience will be much more improved by the fact that he will only see the next step methods available, NO build method until is the right time to build the object.
-## Class diagram
-![alt text](./etc/step-builder.png "Step Builder")
+## Real World Example
+
+Imagine you are building a configuration object for a database connection. The connection has various optional parameters such as host, port, username, password, and others. Using the Step Builder pattern, you can set these parameters in a clean and readable way:
+
+```java
+DatabaseConnection connection = new DatabaseConnection.Builder()
+ .setHost("localhost")
+ .setPort(3306)
+ .setUsername("user")
+ .setPassword("password")
+ .setSSL(true)
+ .build();
+```
+
+## In Plain Words
+
+The Step Builder pattern allows you to construct complex objects by breaking down the construction process into a series of steps. Each step corresponds to setting a particular attribute or configuration option of the object. This results in more readable and maintainable code, especially when dealing with objects that have numerous configuration options.
+
+## Wikipedia Says
+
+According to Wikipedia, the Step Builder pattern is a creational design pattern in which an object is constructed step by step. It involves a dedicated 'director' class, which orchestrates the construction process through a series of 'builder' classes, each responsible for a specific aspect of the object's configuration. This pattern is particularly useful when dealing with objects that have a large number of optional parameters.
+
+## Programmatic Example
+
+Assuming you have a class `Product` with several configurable attributes, a Step Builder for it might look like this:
+
+```java
+public class Product {
+ private String name;
+ private double price;
+ private int quantity;
+
+ // private constructor to force the use of the builder
+ private Product(String name, double price, int quantity) {
+
+ this.name = name;
+ this.price = price;
+ this.quantity = quantity;
+
+ }
+
+ public static class Builder {
+ private String name;
+ private double price;
+ private int quantity;
+
+ public Builder setName(String name) {
+ this.name = name;
+ return this;
+ }
+
+ public Builder setPrice(double price) {
+ this.price = price;
+ return this;
+ }
+
+ public Builder setQuantity(int quantity) {
+ this.quantity = quantity;
+ return this;
+ }
+
+ public Product build() {
+ return new Product(name, price, quantity);
+ }
+ }
+}
+
+// Usage
+Product product = new Product.Builder()
+ .setName("Example Product")
+ .setPrice(29.99)
+ .setQuantity(100)
+ .build();
+```
+
+This example demonstrates how you can use the Step Builder pattern to create a `Product` object with a customizable set of attributes. Each method in the builder corresponds to a step in the construction process.
## Applicability
Use the Step Builder pattern when the algorithm for creating a complex object should be independent of the parts that make up the object and how they're assembled the construction process must allow different representations for the object that's constructed when in the process of constructing the order is important.
+## Another example with class diagram
+![alt text](./etc/step-builder.png "Step Builder")
+
+
## Credits
* [Marco Castigliego - Step Builder](http://rdafbn.blogspot.co.uk/2012/07/step-builder-pattern_28.html)
| null | train | test | 2023-08-27T13:40:17 | "2022-10-29T20:04:58Z" | iluwatar | train |
iluwatar/java-design-patterns/2230_2622 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/2230 | iluwatar/java-design-patterns/2622 | [
"timestamp(timedelta=66.0, similarity=0.8982657430650325)"
] | 72da91e561421d9fc9e6a15fd8190ad4d16c00c8 | f9ae5961e6cc3dbb3c3cee16d56fb1f39c8e5b0f | [
"Hi! Could I please be assigned to this issue?",
"Hey Iluwatar! I've finished my addition, please let me know if you need me to change anything!"
] | [] | "2023-10-08T06:22:32Z" | [
"type: feature",
"epic: documentation"
] | Explanation for Feature Toggle | In this issue, let's add a proper explanation for the pattern.
Acceptance criteria
- The pattern's README.md has been amended with an explanation
- The explanation consists of
- Real world example
- In plain words
- Wikipedia says
- Programmatic example
| [
"feature-toggle/README.md"
] | [
"feature-toggle/README.md"
] | [] | diff --git a/feature-toggle/README.md b/feature-toggle/README.md
index 915a255690da..982108bc7440 100644
--- a/feature-toggle/README.md
+++ b/feature-toggle/README.md
@@ -10,10 +10,53 @@ tag:
Feature Flag
## Intent
-Used to switch code execution paths based on properties or groupings. Allowing new features to be released, tested
-and rolled out. Allowing switching back to the older feature quickly if needed. It should be noted that this pattern,
-can easily introduce code complexity. There is also cause for concern that the old feature that the toggle is eventually
-going to phase out is never removed, causing redundant code smells and increased maintainability.
+A technique used in software development to control and manage the rollout of specific features or functionality in a
+program without changing the code. It can act as an on/off switch for features depending on the status or properties of
+other values in the program. This is similar to A/B testing, where features are rolled out based on properties such as
+location or device. Implementing this design pattern can increase code complexity, and it is important to remember to
+remove redundant code if this design pattern is being used to phase out a system or feature.
+
+## Explanation
+Real-world Example
+> This design pattern works really well in any sort of development, in particular mobile development. Say you want to
+> introduce a feature such as dark mode, but you want to ensure that the feature works correctly and don't want to roll
+> out the feature to everyone immediately. You write in the code, and have it switched off as default. From here, it is
+> easy to turn on the code for specific users based on selection criteria, or randomly. This will also allow the feature
+> to be turned off easily without any drastic changes to the code, or any need for redeployment or updates.
+
+In plain words
+> Feature Toggle is a way to introduce new features gradually instead of deployment all at once.
+
+Wikipedia says
+> A feature toggle in software development provides an alternative to maintaining multiple feature branches in source
+> code. A condition within the code enables or disables a feature during runtime. In agile settings the toggle is
+> used in production, to switch on the feature on demand, for some or all the users.
+
+## Programmatic Example
+This example shows Java code that allows a feature to show when it is enabled by the developer, and when a user is a
+Premium member of the application. This is useful for subscription locked features.
+```java
+public class FeatureToggleExample {
+ // Bool for feature enabled or disabled
+ private static boolean isNewFeatureEnabled = false;
+
+ public static void main(String[] args) {
+ boolean userIsPremium = true; // Example: Check if the user is a premium user
+
+ // Check if the new feature should be enabled for the user
+ if (userIsPremium && isNewFeatureEnabled) {
+ // User is premium and the new feature is enabled
+ showNewFeature();
+ }
+ }
+
+ private static void showNewFeature() {
+ // If user is allowed to see locked feature, this is where the code would go
+ }
+}
+```
+The code shows how simple it is to implement this design pattern, and the criteria can be further refined or broadened
+should the developers choose to do so.
## Class diagram
![alt text](./etc/feature-toggle.png "Feature Toggle")
@@ -24,7 +67,20 @@ Use the Feature Toggle pattern when
* Giving different features to different users.
* Rolling out a new feature incrementally.
* Switching between development and production environments.
+* Quickly disable problematic features
+* External management of feature deployment
+* Ability to maintain multiple version releases of a feature
+* 'Hidden' deployment, releasing a feature in code for designated testing but not publicly making it available
+
+## Consequences
+Consequences involved with using the Feature Toggle pattern
+
+* Code complexity is increased
+* Testing of multiple states is harder and more time-consuming
+* Confusion between friends on why features are missing
+* Keeping documentation up to date with all features can be difficult
## Credits
* [Martin Fowler 29 October 2010 (2010-10-29).](http://martinfowler.com/bliki/FeatureToggle.html)
+* [Feature Toggle - Java Design Patterns](https://java-design-patterns.com/patterns/feature-toggle/)
| null | val | test | 2023-10-08T11:09:28 | "2022-10-29T19:59:15Z" | iluwatar | train |
iluwatar/java-design-patterns/2249_2634 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/2249 | iluwatar/java-design-patterns/2634 | [
"timestamp(timedelta=77.0, similarity=0.9156512772325784)",
"keyword_pr_to_issue"
] | b86f2357b0546f346a889d57a56f0c42346b2fcb | 4d9b8b4d0fa34dd31deb3f273d50c56806a25cbb | [] | [] | "2023-10-11T05:31:13Z" | [
"info: help wanted",
"type: feature",
"epic: documentation"
] | Explanation for Object Mother | In this issue, let's add a proper explanation for the pattern.
Acceptance criteria
- The pattern's README.md has been amended with an explanation
- The explanation consists of
- Real world example
- In plain words
- Wikipedia says
- Programmatic example
| [
"object-mother/README.md"
] | [
"object-mother/README.md"
] | [] | diff --git a/object-mother/README.md b/object-mother/README.md
index 99d49af4b04d..4f2a6664cd48 100644
--- a/object-mother/README.md
+++ b/object-mother/README.md
@@ -7,7 +7,7 @@ tag:
---
## Object Mother
-Define a factory of immutable content with separated builder and factory interfaces.
+It is used to define a factory of immutable content with separated builder and factory interfaces.
## Class diagram
![alt text](./etc/object-mother.png "Object Mother")
@@ -19,6 +19,69 @@ Use the Object Mother pattern when
* You want to reduce code for creation of objects in tests
* Every test should run with fresh data
+
+## Understanding the Object Mother Pattern
+
+### Real-World Scenario
+Imagine you're developing a Java application for a travel agency. In your system, there are different types of travelers, such as tourists, business travelers, and travel agents, each with specific attributes and behaviors. To perform thorough testing, you need to create and manipulate these traveler objects in various contexts. The Object Mother Pattern can help you generate consistent and predefined traveler objects for testing purposes, ensuring that your tests are based on known, reliable data.
+
+### In Plain Terms
+The Object Mother Pattern is a design pattern used in Java to simplify the creation of objects with specific configurations, especially for testing. Instead of manually constructing objects with varying properties for each test case, you create a dedicated "Object Mother" class or method that produces these objects with predefined settings. This ensures that you have consistent and predictable test data, making your tests more reliable and easier to manage.
+
+### Overview from a Testing Perspective
+The Object Mother Pattern is a testing-related design pattern that assists in maintaining a consistent and reliable testing environment. It allows you to define and create objects with specific attributes, helping you ensure that your tests produce consistent and predictable results, making it easier to spot issues and maintain your test suite.
+
+### Practical Usage in Testing
+In software testing, especially unit testing, the Object Mother Pattern is invaluable. It helps ensure that your tests are not influenced by unpredictable data, thus making your tests more robust and repeatable. By centralizing the creation of test objects in an Object Mother, you can easily adapt your test data to different scenarios.
+
+### Example in Java
+Here's an illustrative Java example of the Object Mother Pattern within the context of a travel agency application:
+
+```java
+class Traveler {
+ private String name;
+ private int age;
+ private boolean isBusinessTraveler;
+
+ // Constructor and methods for the traveler
+ // ...
+
+ // Getter and setter methods
+ // ...
+}
+
+class TravelerMother {
+ public static Traveler createTourist(String name, int age) {
+ Traveler traveler = new Traveler();
+ traveler.setName(name);
+ traveler.setAge(age);
+ traveler.setBusinessTraveler(false);
+ return traveler;
+ }
+
+ public static Traveler createBusinessTraveler(String name, int age) {
+ Traveler traveler = new Traveler();
+ traveler.setName(name);
+ traveler.setAge(age);
+ traveler.setBusinessTraveler(true);
+ return traveler;
+ }
+}
+
+public class TravelAgency {
+ public static void main(String[] args) {
+ // Using the Object Mother to create traveler objects for testing
+ Traveler tourist = TravelerMother.createTourist("Alice", 28);
+ Traveler businessTraveler = TravelerMother.createBusinessTraveler("Bob", 35);
+
+ // Now you have consistent traveler objects for testing.
+ }
+}
+
+```
+
+In this example, TravelerMother is the Object Mother class responsible for generating predefined Traveler objects with specific configurations. This approach ensures that you have consistent test data for various scenarios in a travel agency application, enhancing the reliability and effectiveness of your testing efforts.
+
## Credits
* [Answer by David Brown](http://stackoverflow.com/questions/923319/what-is-an-objectmother) to the stackoverflow question: [What is an ObjectMother?](http://stackoverflow.com/questions/923319/what-is-an-objectmother)
| null | train | test | 2023-10-11T08:17:56 | "2022-10-29T20:00:10Z" | iluwatar | train |
iluwatar/java-design-patterns/2631_2641 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/2631 | iluwatar/java-design-patterns/2641 | [
"timestamp(timedelta=40.0, similarity=0.8452084574676992)"
] | 54d628032245b1f6b00ecc6261b96b278440a7a6 | 09b9ee2f5f1d0c957421fbf18b09f0eccaa16502 | [
"Subtask of https://github.com/iluwatar/java-design-patterns/issues/2282",
"Pls assign it to me i will do it",
"This issue has been automatically marked as stale because it has not had recent activity. The issue will be unassigned if no further activity occurs. Thank you for your contributions.\n"
] | [] | "2023-10-13T00:01:53Z" | [
"type: feature",
"status: stale",
"epic: translation"
] | Translate the README file of the callback pattern to Korean & Place it under localization/ko/callback | ### #2282 Translate the README file of the callback pattern to Korean & Place it under localization/ko/callback | [] | [
"localization/ko/callback/README.md"
] | [] | diff --git a/localization/ko/callback/README.md b/localization/ko/callback/README.md
new file mode 100644
index 000000000000..b11c6dea68e7
--- /dev/null
+++ b/localization/ko/callback/README.md
@@ -0,0 +1,71 @@
+---
+title: Callback
+category: Idiom
+language: ko
+tag:
+- Reactive
+---
+
+## 의도
+
+콜백은 다른 코드에 인자로 넘어가는 실행 가능한 코드의 일부로, 인자는 적절한 시점에 다시 호출 (실행) 된다.
+
+## 설명
+
+실제 예제
+
+> 실행 항목이 완료되었다는 사실을 고지받아야 할 때, 콜백 함수를 실행 항목을 담당하는 함수에게 넘겨주고 다시 호출할 때까지 기다린다.
+
+명확하게는
+
+> 콜백은 실행 함수에 넘겨져서 정의된 순간에 호출되는 함수이다.
+
+위키피디아의 정의는
+
+> 컴퓨터 프로그래밍에서, "사후-호출" 함수로도 알려진 콜백은, 다른 코드에 인자로 넘겨지는 실행 가능한 코드를 말한다;
+> 다른 코드는 정해진 시간에 인자를 다시 호출 (실행) 할 것으로 기대되어진다.
+
+**코드 예제**
+
+콜백은 하나의 메서드를 가지고 있는 단순한 인터페이스이다.
+
+```java
+public interface Callback {
+
+ void call();}
+```
+
+다음으로 작업의 실행이 끝나고 나서 콜백을 실행시킬 Task 클래스를 정의한다.
+
+```java
+public abstract class Task {
+
+ final void executeWith(Callback callback) { execute(); Optional.ofNullable(callback).ifPresent(Callback::call); }
+ public abstract void execute();}
+
+@Slf4j
+public final class SimpleTask extends Task {
+
+ @Override public void execute() { LOGGER.info("우선순위의 작업을 마친 이후 콜백 메서드를 호출한다.");
+ }}
+```
+
+마지막으로, 다음은 작업을 실행한 후 마쳤을 때 콜백을 받는 방법의 예시이다.
+
+```java
+ var task = new SimpleTask(); task.executeWith(() -> LOGGER.info("완료되었음."));
+```
+
+## 클래스 다이어그램
+
+![alt text](./etc/callback.png "callback")
+
+## 적용
+
+콜백 패턴을 사용할 수 있을 때는
+
+* 동기 또는 비동기적인 임의의 행위가 정의된 어떠한 행위의 실행 이후에 수행되어야 할 때이다.
+
+## 실질적인 예시들
+
+* [CyclicBarrier](http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/CyclicBarrier.html#CyclicBarrier%28int,%20java.lang.Runnable%29) 생성자는 장벽이 넘어질 때마다 발동되는 콜백을 인자로 받을 수 있다.
\ No newline at end of file
| null | train | test | 2024-02-25T13:47:19 | "2023-10-10T14:49:25Z" | Nickolodeon98 | train |
iluwatar/java-design-patterns/2229_2645 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/2229 | iluwatar/java-design-patterns/2645 | [
"timestamp(timedelta=1.0, similarity=0.9117714487460985)"
] | b86f2357b0546f346a889d57a56f0c42346b2fcb | d3cc529f6cbcb826d816e20d253ed1b618b7fad6 | [
"Hi @iluwatar,\r\n\r\nI was wondering if you could assign this issue to me as I would like to work on it.\r\n\r\nRegards,\r\nJerry"
] | [] | "2023-10-14T04:05:21Z" | [
"type: feature",
"epic: documentation"
] | Explanation for Extension Objects | In this issue, let's add a proper explanation for the pattern.
Acceptance criteria
- The pattern's README.md has been amended with an explanation
- The explanation consists of
- Real world example
- In plain words
- Wikipedia says
- Programmatic example
| [
"extension-objects/README.md"
] | [
"extension-objects/README.md"
] | [] | diff --git a/extension-objects/README.md b/extension-objects/README.md
index fa00d3d5319d..5ecc08efb394 100644
--- a/extension-objects/README.md
+++ b/extension-objects/README.md
@@ -6,10 +6,120 @@ tag:
- Extensibility
---
+# Extention Objects Pattern
+
## Intent
Anticipate that an object’s interface needs to be extended in the future. Additional
interfaces are defined by extension objects.
+## Explanation
+Real-world example
+
+> Suppose you are developing a Java-based game for a client, and in the middle of the development process, new features are suggested. The Extension Objects pattern empowers your program to adapt to unforeseen changes with minimal refactoring, especially when integrating additional functionalities into your project.
+
+In plain words
+
+> The Extension Objects pattern is used to dynamically add functionality to objects without modifying their core classes. It is a behavioural design pattern used for adding new functionality to existing classes and objects within a program. This pattern provides programmers with the ability to extend/modify class functionality without having to refactor existing source code.
+
+Wikipedia says
+
+> In object-oriented computer programming, an extension objects pattern is a design pattern added to an object after the original object was compiled. The modified object is often a class, a prototype or a type. Extension object patterns are features of some object-oriented programming languages. There is no syntactic difference between calling an extension method and calling a method declared in the type definition.
+
+**Programmatic example**
+
+The aim of utilising the Extension Objects pattern is to implement new features/functionality without having to refactor every class.
+The following examples shows utilising this pattern for an Enemy class extending Entity within a game:
+
+Primary App class to execute our program from.
+```java
+public class App {
+ public static void main(String[] args) {
+ Entity enemy = new Enemy("Enemy");
+ checkExtensionsForEntity(enemy);
+ }
+
+ private static void checkExtensionsForEntity(Entity entity) {
+ Logger logger = Logger.getLogger(App.class.getName());
+ String name = entity.getName();
+ Function<String, Runnable> func = (e) -> () -> logger.info(name + " without " + e);
+
+ String extension = "EnemyExtension";
+ Optional.ofNullable(entity.getEntityExtension(extension))
+ .map(e -> (EnemyExtension) e)
+ .ifPresentOrElse(EnemyExtension::extendedAction, func.apply(extension));
+ }
+}
+```
+Enemy class with initial actions and extensions.
+```java
+class Enemy extends Entity {
+ public Enemy(String name) {
+ super(name);
+ }
+
+ @Override
+ protected void performInitialAction() {
+ super.performInitialAction();
+ System.out.println("Enemy wants to attack you.");
+ }
+
+ @Override
+ public EntityExtension getEntityExtension(String extensionName) {
+ if (extensionName.equals("EnemyExtension")) {
+ return Optional.ofNullable(entityExtension).orElseGet(EnemyExtension::new);
+ }
+ return super.getEntityExtension(extensionName);
+ }
+}
+```
+EnemyExtension class with overriding extendAction() method.
+```java
+class EnemyExtension implements EntityExtension {
+ @Override
+ public void extendedAction() {
+ System.out.println("Enemy has advanced towards you!");
+ }
+}
+```
+Entity class which will be extended by Enemy.
+```java
+class Entity {
+ private String name;
+ protected EntityExtension entityExtension;
+
+ public Entity(String name) {
+ this.name = name;
+ performInitialAction();
+ }
+
+ protected void performInitialAction() {
+ System.out.println(name + " performs the initial action.");
+ }
+
+ public EntityExtension getEntityExtension(String extensionName) {
+ return null;
+ }
+
+ public String getName() {
+ return name;
+ }
+}
+```
+EntityExtension interface to be used by EnemyExtension.
+```java
+interface EntityExtension {
+ void extendedAction();
+}
+```
+Program output:
+```markdown
+Enemy performs the initial action.
+Enemy wants to attack you.
+Enemy has advanced towards you!
+```
+In this example, the Extension Objects pattern allows the enemy entity to perform unique initial actions and advanced actions when specific extensions are applied. This pattern provides flexibility and extensibility to the codebase while minimizing the need for major code changes.
+
+
## Class diagram
![Extension_objects](./etc/extension_obj.png "Extension objects")
| null | val | test | 2023-10-11T08:17:56 | "2022-10-29T19:59:12Z" | iluwatar | train |
iluwatar/java-design-patterns/2248_2706 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/2248 | iluwatar/java-design-patterns/2706 | [
"keyword_pr_to_issue"
] | f63c5dd46ddaaeaa6c2844dd7db6192fafce616a | 7fdd5742a229c6c19be3284224f68804515bc3b5 | [
"hey, I want to work on this issue can you assign me this please . "
] | [] | "2023-10-17T14:39:44Z" | [
"type: feature",
"epic: documentation"
] | Explanation for Naked Objects | In this issue, let's add a proper explanation for the pattern.
Acceptance criteria
- The pattern's README.md has been amended with an explanation
- The explanation consists of
- Real world example
- In plain words
- Wikipedia says
- Programmatic example
| [
"naked-objects/README.md"
] | [
"naked-objects/README.md"
] | [] | diff --git a/naked-objects/README.md b/naked-objects/README.md
index b091c55d0414..8ed8210de4d2 100644
--- a/naked-objects/README.md
+++ b/naked-objects/README.md
@@ -3,40 +3,142 @@ title: Naked Objects
category: Architectural
language: en
tag:
-- Decoupling
-- Extensibility
-- Presentation
+ - Decoupling
+ - Extensibility
+ - Presentation
---
## Intent
-The Naked Objects architectural pattern is well suited for rapid
-prototyping. Using the pattern, you only need to write the domain objects,
-everything else is autogenerated by the framework. This pattern enforces a strong domain-driven design principle as the generated UI directly reflects your domain objects and allows users to view as well as interact with them directly (hence the 'naked' part). This allows the users to become more of a problem-solver rather than a process-follower when using the UI.
+
+> The naked object design pattern is a way to build user interfaces (UIs) for software applications that is based on the idea of direct manipulation. This means that users interact directly with the underlying domain objects of the application, without any intermediary UI elements.
+
+> The naked object pattern is implemented by exposing the domain objects to the user in a way that is both meaningful and accessible. This is typically done by generating a UI automatically from the domain object definitions. The UI presents the domain objects to the user in a simple and straightforward way, allowing them to create, retrieve, update, and delete objects, as well as invoke methods on them.
+
+> The naked object pattern has a number of advantages, including:
+
+> 1. <ins>Reduced development time and cost</ins>: The naked object pattern can significantly reduce the time and cost required to develop and maintain a software application. This is because the UI is generated automatically, and the domain objects are designed to be both user-visible and manipulatable.
+
+> 2. <ins>Empowered users</ins>: The naked object pattern gives users direct access to the underlying domain objects of the application. This allows them to interact with the application in a way that is natural and intuitive.
+
+> 3. <ins>Increased flexibility and adaptability</ins>: The naked object pattern is highly flexible and adaptable. This is because the UI is generated from the domain object definitions, which means that the UI can be easily changed as the domain model evolves.
## Explanation
-
+
**In plain words**
-> Naked objects allows you to rapidly generate objected-oriented UI that allows users to perform tasks in ways that they want.
-
+> Imagine you are building a software application to manage a customer database. You could use the naked object pattern to build the UI for this application as follows:
+
+> 1. Define the domain objects for your application. This includes objects such as Customer, Order, and Product.
+
+> 2. Implement the business logic for your application on these domain objects. For example, you could implement methods to create a new customer, add a product to an order, or calculate the total price of an order.
+
+> 3. Use a naked object framework to generate a UI for your application from the domain object definitions.
+
+> The generated UI will present the domain objects to the user in a simple and straightforward way. The user will be able to create, retrieve, update, and delete customers, orders, and products, as well as invoke methods on them.
+
+For example, the user could create a new customer by entering the customer's name, address, and phone number into the UI. The user could also retrieve a list of all customers by clicking a button. To update a customer's information, the user could simply change the corresponding values in the UI and click a save button.
+
**Wikipedia says**
+
> Naked objects is an architectural pattern used in software engineering. It is defined by three principles:
->
+>
> 1. All business logic should be encapsulated onto the domain objects. This principle is not unique to naked objects; it is a strong commitment to encapsulation.
> 2. The user interface should be a direct representation of the domain objects, with all user actions consisting of creating, retrieving, or invoking methods on domain objects. This principle is not unique to naked objects: it is an interpretation of an object-oriented user interface.
>
-> The naked object pattern's innovative feature arises by combining the 1st and 2nd principles into a 3rd principle:
-> 3. The user interface shall be entirely automatically created from the definitions of the domain objects. This may be done using reflection or source code generation.
+> The naked object pattern's innovative feature arises by combining the 1st and 2nd principles into a 3rd principle: 3. The user interface shall be entirely automatically created from the definitions of the domain objects. This may be done using reflection or source code generation.
+
+## Programmatic example
+
+> Certainly, here's a programmatic example section for the Naked Objects pattern:
+
+## Programmatic Example
+
+In the context of the Naked Objects pattern, let's consider a simplified example with domain objects representing books and authors. The example demonstrates how the Naked Objects pattern can be applied to create a user interface for managing a library catalog.
+
+Suppose we have the following domain objects in a Java-based application:
+
+````java
+@DomainObject
+public class Book {
+ @Property
+ private String title;
+
+ @Property
+ private String author;
+
+ @Action
+ public void borrow() {
+ // Implement borrowing logic here
+ }
+}
+
+@DomainObject
+public class Author {
+ @Property
+ private String name;
+
+ @Collection
+ public List<Book> getBooks() {
+ // Implement logic to retrieve books by this author
+ }
+
+ @Action
+ public Book createBook(String title) {
+ // Implement logic to create a new book by this author
+ }
+}
+````
+
+
+> In this example, we define two domain objects: Book and Author. The Book class has properties for the title and author, as well as an action to borrow the book. The Author class has a property for the author's name, a collection of books they have written, and an action to create a new book.
+
+> With the Naked Objects framework or tool, the user interface for managing books and authors can be automatically generated based on these domain object definitions. Users can interact with the generated UI to create, retrieve, update, and delete books and authors directly through a user-friendly interface.
+> Here's how you can use these domain objects to create and interact with books and authors programmatically:
+
+```java
+var author = new Author();
+author.setName("J.K. Rowling");
+var book = author.createBook("Harry Potter and the Philosopher's Stone");
+book.setAuthor(author);
+book.borrow();
+
+var booksByAuthor = author.getBooks();
+
+```
+> This example demonstrates how the Naked Objects pattern can be implemented in a Java-based application with domain objects for books and authors. Users can directly manipulate these domain objects through the generated user interface.
+
## Applicability
-Use the Naked Objects pattern when
-* You are prototyping and need fast development cycle
-* An autogenerated user interface is good enough
-* You want to automatically publish the domain as REST services
+> The naked objects pattern is applicable to a wide range of software applications, but it is particularly well-suited for applications where users need to have direct access to the underlying data model. This is often the case in business applications, such as:
+
+* Customer relationship management (CRM) systems
+* Enterprise resource planning (ERP) systems
+* Human resources (HR) systems
+* Order management systems
+* Inventory management systems
+* Asset management systems
+* Project management systems
+* Knowledge management systems
+
+> The naked objects pattern can also be used to build UIs for scientific and engineering applications, such as:
+
+* Data analysis applications
+* Simulation applications
+* Modeling applications
+* Visualization applications
+>In general, the naked objects pattern is a good choice for any application where users need to be able to create, retrieve, update, and delete data, as well as run complex reports and analyses on that data.
+
+## Known uses
+> 1. Here are some specific examples of applications that have been built using the naked objects pattern:
+
+> 2. The Department of Social and Family Affairs in Ireland uses the naked objects pattern for its Child Benefit Administration system.
+
+> 3. The UK National Health Service uses the naked objects pattern for its Electronic Patient Record system.
+
+> 4. The Australian Taxation Office uses the naked objects pattern for its tax return processing system.
-## Known uses
-> The Department of Social and Family Affairs in Ireland, responsible for social welfare payments, has successfully incorporated the naked objects pattern for re-designing their existing Child Benefit Administration system architecture. A case study evaluation of the project shows that users had positive responses to the increased flexibility of working with the new system and that it is easier now to respond to future changes.
+> 5. The US Department of Defense uses the naked objects pattern for its logistics management system.
## Quick start
@@ -48,3 +150,4 @@ Apache Isis is a Java framework that implements the naked objects pattern. Check
* [Apache Isis - Introducing Apache Isis](https://isis.apache.org/versions/1.16.0/pages/downloadable-presentations/resources/downloadable-presentations/IntroducingApacheIsis-notes.pdf)
+````
| null | test | test | 2023-10-15T15:45:17 | "2022-10-29T20:00:07Z" | iluwatar | train |
iluwatar/java-design-patterns/2255_2707 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/2255 | iluwatar/java-design-patterns/2707 | [
"keyword_pr_to_issue"
] | f63c5dd46ddaaeaa6c2844dd7db6192fafce616a | b186ff5e731fa3c1654ccfa812533b6aa61bf354 | [
"I want to contribute on this. Could you please assign me?"
] | [] | "2023-10-17T19:46:37Z" | [
"type: feature",
"epic: documentation"
] | Explanation for Queue-Based Load Leveling | In this issue, let's add a proper explanation for the pattern.
Acceptance criteria
- The pattern's README.md has been amended with an explanation
- The explanation consists of
- Real world example
- In plain words
- Wikipedia says
- Programmatic example
| [
"queue-load-leveling/README.md"
] | [
"queue-load-leveling/README.md"
] | [] | diff --git a/queue-load-leveling/README.md b/queue-load-leveling/README.md
index 5bffdcb2958c..49c37e6238dc 100644
--- a/queue-load-leveling/README.md
+++ b/queue-load-leveling/README.md
@@ -14,6 +14,281 @@ intermittent heavy loads that may otherwise cause the service to fail or the tas
This pattern can help to minimize the impact of peaks in demand on availability and responsiveness
for both the task and the service.
+## Explanation
+
+Real world example
+> A Microsoft Azure web role stores data by using a separate storage service. If a large number of instances of the web
+> role run concurrently, it is possible that the storage service could be overwhelmed and be unable to respond to requests
+> quickly enough to prevent these requests from timing out or failing.
+
+In plain words
+> Makes resource-load balanced by ensuring an intermediate data structure like queue that makes bridge
+> between service-takers and service-givers. Where both takers and givers are running asynchronously and
+> service-takers can tolerate some amount of delay to get feedback.
+>
+
+Wikipedia says
+
+> In computing, load balancing is the process of distributing a set of tasks over a set of resources
+> (computing units), with the aim of making their overall processing more efficient. Load balancing can
+> optimize the response time and avoid unevenly overloading some compute nodes while other compute nodes
+> are left idle.
+
+**Programmatic Example**
+
+TaskGenerator implements Task, runnable interfaces. Hence, It runs asynchronously.
+
+```java
+/**
+ * Task Interface.
+ */
+public interface Task {
+ void submit(Message msg);
+}
+```
+It submits tasks to ServiceExecutor to serve tasks.
+```java
+/**
+ * TaskGenerator class. Each TaskGenerator thread will be a Worker which submit's messages to the
+ * queue. We need to mention the message count for each of the TaskGenerator threads.
+ */
+@Slf4j
+public class TaskGenerator implements Task, Runnable {
+
+ // MessageQueue reference using which we will submit our messages.
+ private final MessageQueue msgQueue;
+
+ // Total message count that a TaskGenerator will submit.
+ private final int msgCount;
+
+ // Parameterized constructor.
+ public TaskGenerator(MessageQueue msgQueue, int msgCount) {
+ this.msgQueue = msgQueue;
+ this.msgCount = msgCount;
+ }
+
+ /**
+ * Submit messages to the Blocking Queue.
+ */
+ public void submit(Message msg) {
+ try {
+ this.msgQueue.submitMsg(msg);
+ } catch (Exception e) {
+ LOGGER.error(e.getMessage());
+ }
+ }
+
+ /**
+ * Each TaskGenerator thread will submit all the messages to the Queue. After every message
+ * submission TaskGenerator thread will sleep for 1 second.
+ */
+ public void run() {
+ var count = this.msgCount;
+
+ try {
+ while (count > 0) {
+ var statusMsg = "Message-" + count + " submitted by " + Thread.currentThread().getName();
+ this.submit(new Message(statusMsg));
+
+ LOGGER.info(statusMsg);
+
+ // reduce the message count.
+ count--;
+
+ // Make the current thread to sleep after every Message submission.
+ Thread.sleep(1000);
+ }
+ } catch (Exception e) {
+ LOGGER.error(e.getMessage());
+ }
+ }
+}
+```
+It also implements runnable interface and run asynchronously. It retrieves tasks one by one
+from blockingQueue to serve.
+```java
+/**
+ * ServiceExecuotr class. This class will pick up Messages one by one from the Blocking Queue and
+ * process them.
+ */
+@Slf4j
+public class ServiceExecutor implements Runnable {
+
+ private final MessageQueue msgQueue;
+
+ public ServiceExecutor(MessageQueue msgQueue) {
+ this.msgQueue = msgQueue;
+ }
+
+ /**
+ * The ServiceExecutor thread will retrieve each message and process it.
+ */
+ public void run() {
+ try {
+ while (!Thread.currentThread().isInterrupted()) {
+ var msg = msgQueue.retrieveMsg();
+
+ if (null != msg) {
+ LOGGER.info(msg.toString() + " is served.");
+ } else {
+ LOGGER.info("Service Executor: Waiting for Messages to serve .. ");
+ }
+
+ Thread.sleep(1000);
+ }
+ } catch (Exception e) {
+ LOGGER.error(e.getMessage());
+ }
+ }
+}
+```
+
+BlockingQueue data-structure is used in MessageQueue class for acting buffer
+between TaskGenerator to ServiceExecutor.
+
+```java
+public class MessageQueue {
+
+ private final BlockingQueue<Message> blkQueue;
+
+ // Default constructor when called creates Blocking Queue object.
+ public MessageQueue() {
+ this.blkQueue = new ArrayBlockingQueue<>(1024);
+ }
+
+ /**
+ * All the TaskGenerator threads will call this method to insert the Messages in to the Blocking
+ * Queue.
+ */
+ public void submitMsg(Message msg) {
+ try {
+ if (null != msg) {
+ blkQueue.add(msg);
+ }
+ } catch (Exception e) {
+ LOGGER.error(e.getMessage());
+ }
+ }
+
+ /**
+ * All the messages will be retrieved by the ServiceExecutor by calling this method and process
+ * them. Retrieves and removes the head of this queue, or returns null if this queue is empty.
+ */
+ public Message retrieveMsg() {
+ try {
+ return blkQueue.poll();
+ } catch (Exception e) {
+ LOGGER.error(e.getMessage());
+ }
+ return null;
+ }
+}
+```
+TaskGenerator submit message object to ServiceExecutor for serving.
+```java
+/**
+ * Message class with only one parameter.
+ */
+@Getter
+@RequiredArgsConstructor
+public class Message {
+ private final String msg;
+
+ @Override
+ public String toString() {
+ return msg;
+ }
+}
+```
+To simulate the situation ExecutorService is used here. ExecutorService automatically provides a pool of threads and
+an API for assigning tasks to it.
+```java
+public class App {
+
+ //Executor shut down time limit.
+ private static final int SHUTDOWN_TIME = 15;
+
+ /**
+ * Program entry point.
+ *
+ * @param args command line args
+ */
+ public static void main(String[] args) {
+
+ // An Executor that provides methods to manage termination and methods that can
+ // produce a Future for tracking progress of one or more asynchronous tasks.
+ ExecutorService executor = null;
+
+ try {
+ // Create a MessageQueue object.
+ var msgQueue = new MessageQueue();
+
+ LOGGER.info("Submitting TaskGenerators and ServiceExecutor threads.");
+
+ // Create three TaskGenerator threads. Each of them will submit different number of jobs.
+ final var taskRunnable1 = new TaskGenerator(msgQueue, 5);
+ final var taskRunnable2 = new TaskGenerator(msgQueue, 1);
+ final var taskRunnable3 = new TaskGenerator(msgQueue, 2);
+
+ // Create e service which should process the submitted jobs.
+ final var srvRunnable = new ServiceExecutor(msgQueue);
+
+ // Create a ThreadPool of 2 threads and
+ // submit all Runnable task for execution to executor..
+ executor = Executors.newFixedThreadPool(2);
+ executor.submit(taskRunnable1);
+ executor.submit(taskRunnable2);
+ executor.submit(taskRunnable3);
+
+ // submitting serviceExecutor thread to the Executor service.
+ executor.submit(srvRunnable);
+
+ // Initiates an orderly shutdown.
+ LOGGER.info("Initiating shutdown."
+ + " Executor will shutdown only after all the Threads are completed.");
+ executor.shutdown();
+
+ // Wait for SHUTDOWN_TIME seconds for all the threads to complete
+ // their tasks and then shut down the executor and then exit.
+ if (!executor.awaitTermination(SHUTDOWN_TIME, TimeUnit.SECONDS)) {
+ LOGGER.info("Executor was shut down and Exiting.");
+ executor.shutdownNow();
+ }
+ } catch (Exception e) {
+ LOGGER.error(e.getMessage());
+ }
+ }
+}
+```
+
+The console output
+```
+[main] INFO App - Submitting TaskGenerators and ServiceExecutor threads.
+[main] INFO App - Initiating shutdown. Executor will shutdown only after all the Threads are completed.
+[pool-1-thread-2] INFO TaskGenerator - Message-1 submitted by pool-1-thread-2
+[pool-1-thread-1] INFO TaskGenerator - Message-5 submitted by pool-1-thread-1
+[pool-1-thread-1] INFO TaskGenerator - Message-4 submitted by pool-1-thread-1
+[pool-1-thread-2] INFO TaskGenerator - Message-2 submitted by pool-1-thread-2
+[pool-1-thread-1] INFO TaskGenerator - Message-3 submitted by pool-1-thread-1
+[pool-1-thread-2] INFO TaskGenerator - Message-1 submitted by pool-1-thread-2
+[pool-1-thread-1] INFO TaskGenerator - Message-2 submitted by pool-1-thread-1
+[pool-1-thread-2] INFO ServiceExecutor - Message-1 submitted by pool-1-thread-2 is served.
+[pool-1-thread-1] INFO TaskGenerator - Message-1 submitted by pool-1-thread-1
+[pool-1-thread-2] INFO ServiceExecutor - Message-5 submitted by pool-1-thread-1 is served.
+[pool-1-thread-2] INFO ServiceExecutor - Message-4 submitted by pool-1-thread-1 is served.
+[pool-1-thread-2] INFO ServiceExecutor - Message-2 submitted by pool-1-thread-2 is served.
+[pool-1-thread-2] INFO ServiceExecutor - Message-3 submitted by pool-1-thread-1 is served.
+[pool-1-thread-2] INFO ServiceExecutor - Message-1 submitted by pool-1-thread-2 is served.
+[pool-1-thread-2] INFO ServiceExecutor - Message-2 submitted by pool-1-thread-1 is served.
+[pool-1-thread-2] INFO ServiceExecutor - Message-1 submitted by pool-1-thread-1 is served.
+[pool-1-thread-2] INFO ServiceExecutor - Service Executor: Waiting for Messages to serve ..
+[pool-1-thread-2] INFO ServiceExecutor - Service Executor: Waiting for Messages to serve ..
+[pool-1-thread-2] INFO ServiceExecutor - Service Executor: Waiting for Messages to serve ..
+[pool-1-thread-2] INFO ServiceExecutor - Service Executor: Waiting for Messages to serve ..
+[main] INFO App - Executor was shut down and Exiting.
+[pool-1-thread-2] ERROR ServiceExecutor - sleep interrupted
+```
+
## Class diagram
![alt text](./etc/queue-load-leveling.gif "queue-load-leveling")
@@ -25,10 +300,8 @@ for both the task and the service.
## Tutorials
* [Queue-Based Load Leveling Pattern](http://java-design-patterns.com/blog/queue-load-leveling/)
-## Real world example
-
-* A Microsoft Azure web role stores data by using a separate storage service. If a large number of instances of the web role run concurrently, it is possible that the storage service could be overwhelmed and be unable to respond to requests quickly enough to prevent these requests from timing out or failing.
## Credits
* [Queue-Based Load Leveling pattern](https://docs.microsoft.com/en-us/azure/architecture/patterns/queue-based-load-leveling)
+* [Load-Balancing](https://www.wikiwand.com/en/Load_balancing_(computing))
| null | train | test | 2023-10-15T15:45:17 | "2022-10-29T20:04:32Z" | iluwatar | train |
iluwatar/java-design-patterns/2247_2716 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/2247 | iluwatar/java-design-patterns/2716 | [
"keyword_pr_to_issue"
] | f63c5dd46ddaaeaa6c2844dd7db6192fafce616a | bb8de8701588261c5c6b0a0bdf3b4b1e122e4263 | [
"Hi @iluwatar, I would like to contribute to this issue. Could you please assign this to me?"
] | [] | "2023-10-21T04:13:32Z" | [
"type: feature",
"epic: documentation"
] | Explanation for Mute Idiom | In this issue, let's add a proper explanation for the pattern.
Acceptance criteria
- The pattern's README.md has been amended with an explanation
- The explanation consists of
- Real world example
- In plain words
- Wikipedia says
- Programmatic example
| [
"mute-idiom/README.md"
] | [
"mute-idiom/README.md"
] | [] | diff --git a/mute-idiom/README.md b/mute-idiom/README.md
index 6e94ce4d989f..1b25e95fcaf5 100644
--- a/mute-idiom/README.md
+++ b/mute-idiom/README.md
@@ -2,23 +2,94 @@
title: Mute Idiom
category: Idiom
language: en
-tag:
- - Decoupling
+tag:
+- Decoupling
---
+
## Intent
Provide a template to suppress any exceptions that either are declared but cannot occur or should only be logged;
while executing some business logic. The template removes the need to write repeated `try-catch` blocks.
+
+## Explanation
+Real World Example
+> The vending machine contained in your office displays a warning when making a transaction. The issue occurs when the
+> customer decides to pay with physical money that is not recognized by the system. However, you and everyone in the office
+> only pays with the company credit card and will never encounter this issue.
+
+In plain words
+> The Mute Idiom design pattern is used to reduce the requirement of catching exceptions when they cannot be thrown or
+> should be ignored when thrown. This applies in cases such as API functions, where the underlying code cannot be changed
+> to include individual use cases.
+
+Programmatic Example
+
+Converting the real-world example into a programmatic representation, we represent an API function as the
+office Vending machine
+
+```java
+
+public class VendingMachine {
+ public void purchaseItem(int itemID, PaymentMethod paymentMethod) throws Exception {
+ if (paymentMethod == PaymentMethod.Cash) {
+ throw new Exception();
+ }
+ else {
+ System.out.println("Here is your item");
+ }
+ }
+}
+```
+
+```java
+public enum PaymentMethod {
+ Card,Cash
+}
+```
+
+We then run our office's daily routine, which involves purchasing items
+from the vending machine with the company card, using the mute pattern to ignore the exceptions that can't be thrown
+```java
+package com.iluwatar.mute;
+
+public class Office {
+ private PaymentMethod companyCard = PaymentMethod.Card;
+ private VendingMachine officeVendingMachine = new VendingMachine();
+
+ public static void main(String[] args) {
+ Office office = new Office();
+ office.dailyRoutine();
+
+ }
+ public void dailyRoutine() {
+ Mute.mute(() -> {
+ officeVendingMachine.purchaseItem(1,companyCard);
+ officeVendingMachine.purchaseItem(1,companyCard);
+ officeVendingMachine.purchaseItem(1,companyCard);
+ });
+ }
+}
+
+```
+
+
## Class diagram
![alt text](./etc/mute-idiom.png "Mute Idiom")
+
## Applicability
Use this idiom when
-
* an API declares some exception but can never throw that exception eg. ByteArrayOutputStream bulk write method.
* you need to suppress some exception just by logging it, such as closing a resource.
+
+
+
## Credits
+
* [JOOQ: Mute Design Pattern](http://blog.jooq.org/2016/02/18/the-mute-design-pattern/)
+
+
+
| null | train | test | 2023-10-15T15:45:17 | "2022-10-29T20:00:05Z" | iluwatar | train |
iluwatar/java-design-patterns/2245_2717 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/2245 | iluwatar/java-design-patterns/2717 | [
"keyword_pr_to_issue"
] | f63c5dd46ddaaeaa6c2844dd7db6192fafce616a | fb507110442bc2a132704c45bdc6364197c0119d | [
"Hi @iluwatar I would like to contribute to this issue. If you give me the opportunity, I will try my best to solve it. Thank you!",
"This issue has been automatically marked as stale because it has not had recent activity. The issue will be unassigned if no further activity occurs. Thank you for your contributions.\n"
] | [
"Avoid removing spaces. They are meant for indentation",
"I'm sorry, I have added the space back"
] | "2023-10-21T04:22:06Z" | [
"type: feature",
"status: stale",
"epic: documentation"
] | Explanation for Monad | In this issue, let's add a proper explanation for the pattern.
Acceptance criteria
- The pattern's README.md has been amended with an explanation
- The explanation consists of
- Real world example
- In plain words
- Wikipedia says
- Programmatic example
| [
"monad/README.md"
] | [
"monad/README.md"
] | [] | diff --git a/monad/README.md b/monad/README.md
index f53632faee70..9ccaaebb98ce 100644
--- a/monad/README.md
+++ b/monad/README.md
@@ -15,6 +15,107 @@ operations:
bind - that takes monadic object and a function from plain object to monadic value and returns monadic value
return - that takes plain type object and returns this object wrapped in a monadic value.
+## Explanation
+
+The Monad pattern provides a way to chain operations together and manage sequencing,
+side effects, and exception handling in a consistent manner.
+
+Real-world example
+
+> Consider a conveyor belt in a factory: items move from one station to another,
+> and each station performs a specific task, with the assurance that every task will be carried out,
+> even if some items are rejected at certain stations.
+
+In plain words
+
+> Monad pattern ensures that each operation is executed regardless of the success or failure of previous ones.
+
+Wikipedia says
+
+> In functional programming, a monad is a structure that combines program fragments (functions)
+> and wraps their return values in a type with additional computation. In addition to defining a
+> wrapping monadic type, monads define two operators: one to wrap a value in the monad type, and
+> another to compose together functions that output values of the monad type (these are known as
+> monadic functions). General-purpose languages use monads to reduce boilerplate code needed for
+> common operations (such as dealing with undefined values or fallible functions, or encapsulating
+> bookkeeping code). Functional languages use monads to turn complicated sequences of functions into
+> succinct pipelines that abstract away control flow, and side-effects.
+
+**Programmatic Example**
+
+Here’s the Monad implementation in Java.
+
+The `Validator` takes an object, validates it against specified predicates, and collects any
+validation errors. The `validate` method allows you to add validation steps, and the `get` method
+either returns the validated object or throws an `IllegalStateException` with a list of validation
+exceptions if any of the validation steps fail.
+
+```java
+public class Validator<T> {
+ private final T obj;
+ private final List<Throwable> exceptions = new ArrayList<>();
+
+ private Validator(T obj) {
+ this.obj = obj;
+ }
+ public static <T> Validator<T> of(T t) {
+ return new Validator<>(Objects.requireNonNull(t));
+ }
+
+ public Validator<T> validate(Predicate<? super T> validation, String message) {
+ if (!validation.test(obj)) {
+ exceptions.add(new IllegalStateException(message));
+ }
+ return this;
+ }
+
+ public <U> Validator<T> validate(
+ Function<? super T, ? extends U> projection,
+ Predicate<? super U> validation,
+ String message
+ ) {
+ return validate(projection.andThen(validation::test)::apply, message);
+ }
+
+ public T get() throws IllegalStateException {
+ if (exceptions.isEmpty()) {
+ return obj;
+ }
+ var e = new IllegalStateException();
+ exceptions.forEach(e::addSuppressed);
+ throw e;
+ }
+}
+```
+
+Next we define an enum `Sex`.
+
+```java
+public enum Sex {
+ MALE, FEMALE
+}
+```
+
+Now we can introduce the `User`.
+
+```java
+public record User(String name, int age, Sex sex, String email) {
+}
+```
+
+And finally, a `User` object is validated for its name, email, and age using the `Validator` monad.
+
+```java
+public static void main(String[] args) {
+ var user = new User("user", 24, Sex.FEMALE, "foobar.com");
+ LOGGER.info(Validator.of(user).validate(User::name, Objects::nonNull, "name is null")
+ .validate(User::name, name -> !name.isEmpty(), "name is empty")
+ .validate(User::email, email -> !email.contains("@"), "email doesn't contains '@'")
+ .validate(User::age, age -> age > 20 && age < 30, "age isn't between...").get()
+ .toString());
+}
+```
+
## Class diagram
![alt text](./etc/monad.png "Monad")
| null | test | test | 2023-10-15T15:45:17 | "2022-10-29T19:59:58Z" | iluwatar | train |
iluwatar/java-design-patterns/2238_2770 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/2238 | iluwatar/java-design-patterns/2770 | [
"keyword_pr_to_issue"
] | 163c3017bb356937d876cd9a05905c012f3b0af6 | 2c35b34c41e14affe08179150b9e66b361ef6851 | [
"I want to contribute on this. Could you please assign me."
] | [] | "2023-11-04T17:03:05Z" | [
"type: feature",
"epic: documentation"
] | Explanation for Leader Election | In this issue, let's add a proper explanation for the pattern.
Acceptance criteria
- The pattern's README.md has been amended with an explanation
- The explanation consists of
- Real world example
- In plain words
- Wikipedia says
- Programmatic example
| [
"leader-election/README.md"
] | [
"leader-election/README.md"
] | [] | diff --git a/leader-election/README.md b/leader-election/README.md
index d2a6ff473e3f..ec57487a9c03 100644
--- a/leader-election/README.md
+++ b/leader-election/README.md
@@ -7,7 +7,821 @@ tag:
---
## Intent
-Leader Election pattern is commonly used in cloud system design. It can help to ensure that task instances select the leader instance correctly and do not conflict with each other, cause contention for shared resources, or inadvertently interfere with the work that other task instances are performing.
+Leader Election pattern is commonly used in cloud system design. It can help to ensure that task
+instances select the leader instance correctly and do not conflict with each other, cause
+contention for shared resources, or inadvertently interfere with the work that other task
+instances are performing.
+
+## Explanation
+
+Real world example
+> In a horizontally scaling cloud-based system, multiple instances of the same task could be
+> running at the same time with each instance serving a different user. If these instances
+> write to a shared resource, it's necessary to coordinate their actions to prevent each instance
+> from overwriting the changes made by the others. In another scenario, if the tasks are performing
+> individual elements of a complex calculation in parallel, the results need to be aggregated
+> when they all complete.
+
+In plain words
+> this pattern is used in distributed cloud-based system where leader must need to act as
+> coordinator/aggregator among horizontal scaling instances for avoiding conflict on shared resources.
+
+Wikipedia says
+> In distributed computing, leader election is the process of designating a single process as
+> the organizer of some task distributed among several computers (nodes).
+
+**Programmatic Example**
+
+Ring algorithm and Bully algorithm implement leader election pattern.
+Each algorithm require every participated instance to have unique ID.
+
+```java
+public interface Instance {
+
+ /**
+ * Check if the instance is alive or not.
+ *
+ * @return {@code true} if the instance is alive.
+ */
+ boolean isAlive();
+
+ /**
+ * Set the health status of the certain instance.
+ *
+ * @param alive {@code true} for alive.
+ */
+ void setAlive(boolean alive);
+
+ /**
+ * Consume messages from other instances.
+ *
+ * @param message Message sent by other instances
+ */
+ void onMessage(Message message);
+
+}
+```
+
+Abstract class who implements Instance and Runnable interfaces.
+```java
+public abstract class AbstractInstance implements Instance, Runnable {
+
+ protected static final int HEARTBEAT_INTERVAL = 5000;
+ private static final String INSTANCE = "Instance ";
+
+ protected MessageManager messageManager;
+ protected Queue<Message> messageQueue;
+ protected final int localId;
+ protected int leaderId;
+ protected boolean alive;
+
+ /**
+ * Constructor of BullyInstance.
+ */
+ public AbstractInstance(MessageManager messageManager, int localId, int leaderId) {
+ this.messageManager = messageManager;
+ this.messageQueue = new ConcurrentLinkedQueue<>();
+ this.localId = localId;
+ this.leaderId = leaderId;
+ this.alive = true;
+ }
+
+ /**
+ * The instance will execute the message in its message queue periodically once it is alive.
+ */
+ @Override
+ @SuppressWarnings("squid:S2189")
+ public void run() {
+ while (true) {
+ if (!this.messageQueue.isEmpty()) {
+ this.processMessage(this.messageQueue.remove());
+ }
+ }
+ }
+
+ /**
+ * Once messages are sent to the certain instance, it will firstly be added to the queue and wait
+ * to be executed.
+ *
+ * @param message Message sent by other instances
+ */
+ @Override
+ public void onMessage(Message message) {
+ messageQueue.offer(message);
+ }
+
+ /**
+ * Check if the instance is alive or not.
+ *
+ * @return {@code true} if the instance is alive.
+ */
+ @Override
+ public boolean isAlive() {
+ return alive;
+ }
+
+ /**
+ * Set the health status of the certain instance.
+ *
+ * @param alive {@code true} for alive.
+ */
+ @Override
+ public void setAlive(boolean alive) {
+ this.alive = alive;
+ }
+
+ /**
+ * Process the message according to its type.
+ *
+ * @param message Message polled from queue.
+ */
+ private void processMessage(Message message) {
+ switch (message.getType()) {
+ case ELECTION -> {
+ LOGGER.info(INSTANCE + localId + " - Election Message handling...");
+ handleElectionMessage(message);
+ }
+ case LEADER -> {
+ LOGGER.info(INSTANCE + localId + " - Leader Message handling...");
+ handleLeaderMessage(message);
+ }
+ case HEARTBEAT -> {
+ LOGGER.info(INSTANCE + localId + " - Heartbeat Message handling...");
+ handleHeartbeatMessage(message);
+ }
+ case ELECTION_INVOKE -> {
+ LOGGER.info(INSTANCE + localId + " - Election Invoke Message handling...");
+ handleElectionInvokeMessage();
+ }
+ case LEADER_INVOKE -> {
+ LOGGER.info(INSTANCE + localId + " - Leader Invoke Message handling...");
+ handleLeaderInvokeMessage();
+ }
+ case HEARTBEAT_INVOKE -> {
+ LOGGER.info(INSTANCE + localId + " - Heartbeat Invoke Message handling...");
+ handleHeartbeatInvokeMessage();
+ }
+ default -> {
+ }
+ }
+ }
+
+ /**
+ * Abstract methods to handle different types of message. These methods need to be implemented in
+ * concrete instance class to implement corresponding leader-selection pattern.
+ */
+ protected abstract void handleElectionMessage(Message message);
+
+ protected abstract void handleElectionInvokeMessage();
+
+ protected abstract void handleLeaderMessage(Message message);
+
+ protected abstract void handleLeaderInvokeMessage();
+
+ protected abstract void handleHeartbeatMessage(Message message);
+
+ protected abstract void handleHeartbeatInvokeMessage();
+
+}
+```
+
+```java
+/**
+ * Message used to transport data between instances.
+ */
+@Setter
+@Getter
+@EqualsAndHashCode
+@AllArgsConstructor
+@NoArgsConstructor
+public class Message {
+
+ private MessageType type;
+ private String content;
+
+}
+```
+
+```java
+public interface MessageManager {
+
+ /**
+ * Send heartbeat message to leader instance to check whether the leader instance is alive.
+ *
+ * @param leaderId Instance ID of leader instance.
+ * @return {@code true} if leader instance is alive, or {@code false} if not.
+ */
+ boolean sendHeartbeatMessage(int leaderId);
+
+ /**
+ * Send election message to other instances.
+ *
+ * @param currentId Instance ID of which sends this message.
+ * @param content Election message content.
+ * @return {@code true} if the message is accepted by the target instances.
+ */
+ boolean sendElectionMessage(int currentId, String content);
+
+ /**
+ * Send new leader notification message to other instances.
+ *
+ * @param currentId Instance ID of which sends this message.
+ * @param leaderId Leader message content.
+ * @return {@code true} if the message is accepted by the target instances.
+ */
+ boolean sendLeaderMessage(int currentId, int leaderId);
+
+ /**
+ * Send heartbeat invoke message. This will invoke heartbeat task in the target instance.
+ *
+ * @param currentId Instance ID of which sends this message.
+ */
+ void sendHeartbeatInvokeMessage(int currentId);
+
+}
+```
+These type of messages are used to pass among instances.
+```java
+/**
+ * Message Type enum.
+ */
+public enum MessageType {
+
+ /**
+ * Start the election. The content of the message stores ID(s) of the candidate instance(s).
+ */
+ ELECTION,
+
+ /**
+ * Nodify the new leader. The content of the message should be the leader ID.
+ */
+ LEADER,
+
+ /**
+ * Check health of current leader instance.
+ */
+ HEARTBEAT,
+
+ /**
+ * Inform target instance to start election.
+ */
+ ELECTION_INVOKE,
+
+ /**
+ * Inform target instance to notify all the other instance that it is the new leader.
+ */
+ LEADER_INVOKE,
+
+ /**
+ * Inform target instance to start heartbeat.
+ */
+ HEARTBEAT_INVOKE
+
+}
+```
+Abstract class who implements MessageManager interface. It helps to manage messages among instance.
+```java
+/**
+ * Abstract class of all the message manager classes.
+ */
+public abstract class AbstractMessageManager implements MessageManager {
+
+ /**
+ * Contain all the instances in the system. Key is its ID, and value is the instance itself.
+ */
+ protected Map<Integer, Instance> instanceMap;
+
+ /**
+ * Constructor of AbstractMessageManager.
+ */
+ public AbstractMessageManager(Map<Integer, Instance> instanceMap) {
+ this.instanceMap = instanceMap;
+ }
+
+ /**
+ * Find the next instance with smallest ID.
+ *
+ * @return The next instance.
+ */
+ protected Instance findNextInstance(int currentId) {
+ Instance result = null;
+ var candidateList = instanceMap.keySet()
+ .stream()
+ .filter((i) -> i > currentId && instanceMap.get(i).isAlive())
+ .sorted()
+ .toList();
+ if (candidateList.isEmpty()) {
+ var index = instanceMap.keySet()
+ .stream()
+ .filter((i) -> instanceMap.get(i).isAlive())
+ .sorted()
+ .toList()
+ .get(0);
+ result = instanceMap.get(index);
+ } else {
+ var index = candidateList.get(0);
+ result = instanceMap.get(index);
+ }
+ return result;
+ }
+
+}
+```
+
+Here the implementation of Ring Algorithm
+```java
+/**
+ * Implementation with token ring algorithm. The instances in the system are organized as a ring.
+ * Each instance should have a sequential id and the instance with smallest (or largest) id should
+ * be the initial leader. All the other instances send heartbeat message to leader periodically to
+ * check its health. If one certain instance finds the server done, it will send an election message
+ * to the next alive instance in the ring, which contains its own ID. Then the next instance add its
+ * ID into the message and pass it to the next. After all the alive instances' ID are add to the
+ * message, the message is send back to the first instance and it will choose the instance with
+ * smallest ID to be the new leader, and then send a leader message to other instances to inform the
+ * result.
+ */
+@Slf4j
+public class RingInstance extends AbstractInstance {
+ private static final String INSTANCE = "Instance ";
+
+ /**
+ * Constructor of RingInstance.
+ */
+ public RingInstance(MessageManager messageManager, int localId, int leaderId) {
+ super(messageManager, localId, leaderId);
+ }
+
+ /**
+ * Process the heartbeat invoke message. After receiving the message, the instance will send a
+ * heartbeat to leader to check its health. If alive, it will inform the next instance to do the
+ * heartbeat. If not, it will start the election process.
+ */
+ @Override
+ protected void handleHeartbeatInvokeMessage() {
+ try {
+ var isLeaderAlive = messageManager.sendHeartbeatMessage(this.leaderId);
+ if (isLeaderAlive) {
+ LOGGER.info(INSTANCE + localId + "- Leader is alive. Start next heartbeat in 5 second.");
+ Thread.sleep(HEARTBEAT_INTERVAL);
+ messageManager.sendHeartbeatInvokeMessage(this.localId);
+ } else {
+ LOGGER.info(INSTANCE + localId + "- Leader is not alive. Start election.");
+ messageManager.sendElectionMessage(this.localId, String.valueOf(this.localId));
+ }
+ } catch (InterruptedException e) {
+ LOGGER.info(INSTANCE + localId + "- Interrupted.");
+ }
+ }
+
+ /**
+ * Process election message. If the local ID is contained in the ID list, the instance will select
+ * the alive instance with smallest ID to be the new leader, and send the leader inform message.
+ * If not, it will add its local ID to the list and send the message to the next instance in the
+ * ring.
+ */
+ @Override
+ protected void handleElectionMessage(Message message) {
+ var content = message.getContent();
+ LOGGER.info(INSTANCE + localId + " - Election Message: " + content);
+ var candidateList = Arrays.stream(content.trim().split(","))
+ .map(Integer::valueOf)
+ .sorted()
+ .toList();
+ if (candidateList.contains(localId)) {
+ var newLeaderId = candidateList.get(0);
+ LOGGER.info(INSTANCE + localId + " - New leader should be " + newLeaderId + ".");
+ messageManager.sendLeaderMessage(localId, newLeaderId);
+ } else {
+ content += "," + localId;
+ messageManager.sendElectionMessage(localId, content);
+ }
+ }
+
+ /**
+ * Process leader Message. The instance will set the leader ID to be the new one and send the
+ * message to the next instance until all the alive instance in the ring is informed.
+ */
+ @Override
+ protected void handleLeaderMessage(Message message) {
+ var newLeaderId = Integer.valueOf(message.getContent());
+ if (this.leaderId != newLeaderId) {
+ LOGGER.info(INSTANCE + localId + " - Update leaderID");
+ this.leaderId = newLeaderId;
+ messageManager.sendLeaderMessage(localId, newLeaderId);
+ } else {
+ LOGGER.info(INSTANCE + localId + " - Leader update done. Start heartbeat.");
+ messageManager.sendHeartbeatInvokeMessage(localId);
+ }
+ }
+
+ /**
+ * Not used in Ring instance.
+ */
+ @Override
+ protected void handleLeaderInvokeMessage() {
+ // Not used in Ring instance.
+ }
+
+ @Override
+ protected void handleHeartbeatMessage(Message message) {
+ // Not used in Ring instance.
+ }
+
+ @Override
+ protected void handleElectionInvokeMessage() {
+ // Not used in Ring instance.
+ }
+
+}
+```
+
+```java
+/**
+ * Implementation of RingMessageManager.
+ */
+public class RingMessageManager extends AbstractMessageManager {
+
+ /**
+ * Constructor of RingMessageManager.
+ */
+ public RingMessageManager(Map<Integer, Instance> instanceMap) {
+ super(instanceMap);
+ }
+
+ /**
+ * Send heartbeat message to current leader instance to check the health.
+ *
+ * @param leaderId leaderID
+ * @return {@code true} if the leader is alive.
+ */
+ @Override
+ public boolean sendHeartbeatMessage(int leaderId) {
+ var leaderInstance = instanceMap.get(leaderId);
+ var alive = leaderInstance.isAlive();
+ return alive;
+ }
+
+ /**
+ * Send election message to the next instance.
+ *
+ * @param currentId currentID
+ * @param content list contains all the IDs of instances which have received this election
+ * message.
+ * @return {@code true} if the election message is accepted by the target instance.
+ */
+ @Override
+ public boolean sendElectionMessage(int currentId, String content) {
+ var nextInstance = this.findNextInstance(currentId);
+ var electionMessage = new Message(MessageType.ELECTION, content);
+ nextInstance.onMessage(electionMessage);
+ return true;
+ }
+
+ /**
+ * Send leader message to the next instance.
+ *
+ * @param currentId Instance ID of which sends this message.
+ * @param leaderId Leader message content.
+ * @return {@code true} if the leader message is accepted by the target instance.
+ */
+ @Override
+ public boolean sendLeaderMessage(int currentId, int leaderId) {
+ var nextInstance = this.findNextInstance(currentId);
+ var leaderMessage = new Message(MessageType.LEADER, String.valueOf(leaderId));
+ nextInstance.onMessage(leaderMessage);
+ return true;
+ }
+
+ /**
+ * Send heartbeat invoke message to the next instance.
+ *
+ * @param currentId Instance ID of which sends this message.
+ */
+ @Override
+ public void sendHeartbeatInvokeMessage(int currentId) {
+ var nextInstance = this.findNextInstance(currentId);
+ var heartbeatInvokeMessage = new Message(MessageType.HEARTBEAT_INVOKE, "");
+ nextInstance.onMessage(heartbeatInvokeMessage);
+ }
+
+}
+```
+```java
+public static void main(String[] args) {
+
+ Map<Integer, Instance> instanceMap = new HashMap<>();
+ var messageManager = new RingMessageManager(instanceMap);
+
+ var instance1 = new RingInstance(messageManager, 1, 1);
+ var instance2 = new RingInstance(messageManager, 2, 1);
+ var instance3 = new RingInstance(messageManager, 3, 1);
+ var instance4 = new RingInstance(messageManager, 4, 1);
+ var instance5 = new RingInstance(messageManager, 5, 1);
+
+ instanceMap.put(1, instance1);
+ instanceMap.put(2, instance2);
+ instanceMap.put(3, instance3);
+ instanceMap.put(4, instance4);
+ instanceMap.put(5, instance5);
+
+ instance2.onMessage(new Message(MessageType.HEARTBEAT_INVOKE, ""));
+
+ final var thread1 = new Thread(instance1);
+ final var thread2 = new Thread(instance2);
+ final var thread3 = new Thread(instance3);
+ final var thread4 = new Thread(instance4);
+ final var thread5 = new Thread(instance5);
+
+ thread1.start();
+ thread2.start();
+ thread3.start();
+ thread4.start();
+ thread5.start();
+
+ instance1.setAlive(false);
+ }
+```
+
+The console output
+```
+[Thread-1] INFO com.iluwatar.leaderelection.AbstractInstance - Instance 2 - Heartbeat Invoke Message handling...
+[Thread-1] INFO com.iluwatar.leaderelection.ring.RingInstance - Instance 2- Leader is not alive. Start election.
+[Thread-2] INFO com.iluwatar.leaderelection.AbstractInstance - Instance 3 - Election Message handling...
+[Thread-2] INFO com.iluwatar.leaderelection.ring.RingInstance - Instance 3 - Election Message: 2
+[Thread-3] INFO com.iluwatar.leaderelection.AbstractInstance - Instance 4 - Election Message handling...
+[Thread-3] INFO com.iluwatar.leaderelection.ring.RingInstance - Instance 4 - Election Message: 2,3
+[Thread-4] INFO com.iluwatar.leaderelection.AbstractInstance - Instance 5 - Election Message handling...
+[Thread-4] INFO com.iluwatar.leaderelection.ring.RingInstance - Instance 5 - Election Message: 2,3,4
+[Thread-1] INFO com.iluwatar.leaderelection.AbstractInstance - Instance 2 - Election Message handling...
+[Thread-1] INFO com.iluwatar.leaderelection.ring.RingInstance - Instance 2 - Election Message: 2,3,4,5
+[Thread-1] INFO com.iluwatar.leaderelection.ring.RingInstance - Instance 2 - New leader should be 2.
+[Thread-2] INFO com.iluwatar.leaderelection.AbstractInstance - Instance 3 - Leader Message handling...
+[Thread-2] INFO com.iluwatar.leaderelection.ring.RingInstance - Instance 3 - Update leaderID
+[Thread-3] INFO com.iluwatar.leaderelection.AbstractInstance - Instance 4 - Leader Message handling...
+[Thread-3] INFO com.iluwatar.leaderelection.ring.RingInstance - Instance 4 - Update leaderID
+[Thread-4] INFO com.iluwatar.leaderelection.AbstractInstance - Instance 5 - Leader Message handling...
+[Thread-4] INFO com.iluwatar.leaderelection.ring.RingInstance - Instance 5 - Update leaderID
+[Thread-1] INFO com.iluwatar.leaderelection.AbstractInstance - Instance 2 - Leader Message handling...
+[Thread-1] INFO com.iluwatar.leaderelection.ring.RingInstance - Instance 2 - Update leaderID
+[Thread-2] INFO com.iluwatar.leaderelection.AbstractInstance - Instance 3 - Leader Message handling...
+[Thread-2] INFO com.iluwatar.leaderelection.ring.RingInstance - Instance 3 - Leader update done. Start heartbeat.
+[Thread-3] INFO com.iluwatar.leaderelection.AbstractInstance - Instance 4 - Heartbeat Invoke Message handling...
+[Thread-3] INFO com.iluwatar.leaderelection.ring.RingInstance - Instance 4- Leader is alive. Start next heartbeat in 5 second.
+```
+Here the implementation of Bully algorithm
+```java
+/**
+ * Impelemetation with bully algorithm. Each instance should have a sequential id and is able to
+ * communicate with other instances in the system. Initially the instance with smallest (or largest)
+ * ID is selected to be the leader. All the other instances send heartbeat message to leader
+ * periodically to check its health. If one certain instance finds the server done, it will send an
+ * election message to all the instances of which the ID is larger. If the target instance is alive,
+ * it will return an alive message (in this sample return true) and then send election message with
+ * its ID. If not, the original instance will send leader message to all the other instances.
+ */
+@Slf4j
+public class BullyInstance extends AbstractInstance {
+ private static final String INSTANCE = "Instance ";
+
+ /**
+ * Constructor of BullyInstance.
+ */
+ public BullyInstance(MessageManager messageManager, int localId, int leaderId) {
+ super(messageManager, localId, leaderId);
+ }
+
+ /**
+ * Process the heartbeat invoke message. After receiving the message, the instance will send a
+ * heartbeat to leader to check its health. If alive, it will inform the next instance to do the
+ * heartbeat. If not, it will start the election process.
+ */
+ @Override
+ protected void handleHeartbeatInvokeMessage() {
+ try {
+ boolean isLeaderAlive = messageManager.sendHeartbeatMessage(leaderId);
+ if (isLeaderAlive) {
+ LOGGER.info(INSTANCE + localId + "- Leader is alive.");
+ Thread.sleep(HEARTBEAT_INTERVAL);
+ messageManager.sendHeartbeatInvokeMessage(localId);
+ } else {
+ LOGGER.info(INSTANCE + localId + "- Leader is not alive. Start election.");
+ boolean electionResult =
+ messageManager.sendElectionMessage(localId, String.valueOf(localId));
+ if (electionResult) {
+ LOGGER.info(INSTANCE + localId + "- Succeed in election. Start leader notification.");
+ messageManager.sendLeaderMessage(localId, localId);
+ }
+ }
+ } catch (InterruptedException e) {
+ LOGGER.info(INSTANCE + localId + "- Interrupted.");
+ }
+ }
+
+ /**
+ * Process election invoke message. Send election message to all the instances with smaller ID. If
+ * any one of them is alive, do nothing. If no instance alive, send leader message to all the
+ * alive instance and restart heartbeat.
+ */
+ @Override
+ protected void handleElectionInvokeMessage() {
+ if (!isLeader()) {
+ LOGGER.info(INSTANCE + localId + "- Start election.");
+ boolean electionResult = messageManager.sendElectionMessage(localId, String.valueOf(localId));
+ if (electionResult) {
+ LOGGER.info(INSTANCE + localId + "- Succeed in election. Start leader notification.");
+ leaderId = localId;
+ messageManager.sendLeaderMessage(localId, localId);
+ messageManager.sendHeartbeatInvokeMessage(localId);
+ }
+ }
+ }
+
+ /**
+ * Process leader message. Update local leader information.
+ */
+ @Override
+ protected void handleLeaderMessage(Message message) {
+ leaderId = Integer.valueOf(message.getContent());
+ LOGGER.info(INSTANCE + localId + " - Leader update done.");
+ }
+
+ private boolean isLeader() {
+ return localId == leaderId;
+ }
+
+ @Override
+ protected void handleLeaderInvokeMessage() {
+ // Not used in Bully Instance
+ }
+
+ @Override
+ protected void handleHeartbeatMessage(Message message) {
+ // Not used in Bully Instance
+ }
+
+ @Override
+ protected void handleElectionMessage(Message message) {
+ // Not used in Bully Instance
+ }
+}
+```
+
+```java
+/**
+ * Implementation of BullyMessageManager.
+ */
+public class BullyMessageManager extends AbstractMessageManager {
+
+ /**
+ * Constructor of BullyMessageManager.
+ */
+ public BullyMessageManager(Map<Integer, Instance> instanceMap) {
+ super(instanceMap);
+ }
+
+ /**
+ * Send heartbeat message to current leader instance to check the health.
+ *
+ * @param leaderId leaderID
+ * @return {@code true} if the leader is alive.
+ */
+ @Override
+ public boolean sendHeartbeatMessage(int leaderId) {
+ var leaderInstance = instanceMap.get(leaderId);
+ var alive = leaderInstance.isAlive();
+ return alive;
+ }
+
+ /**
+ * Send election message to all the instances with smaller ID.
+ *
+ * @param currentId Instance ID of which sends this message.
+ * @param content Election message content.
+ * @return {@code true} if no alive instance has smaller ID, so that the election is accepted.
+ */
+ @Override
+ public boolean sendElectionMessage(int currentId, String content) {
+ var candidateList = findElectionCandidateInstanceList(currentId);
+ if (candidateList.isEmpty()) {
+ return true;
+ } else {
+ var electionMessage = new Message(MessageType.ELECTION_INVOKE, "");
+ candidateList.stream().forEach((i) -> instanceMap.get(i).onMessage(electionMessage));
+ return false;
+ }
+ }
+
+ /**
+ * Send leader message to all the instances to notify the new leader.
+ *
+ * @param currentId Instance ID of which sends this message.
+ * @param leaderId Leader message content.
+ * @return {@code true} if the message is accepted.
+ */
+ @Override
+ public boolean sendLeaderMessage(int currentId, int leaderId) {
+ var leaderMessage = new Message(MessageType.LEADER, String.valueOf(leaderId));
+ instanceMap.keySet()
+ .stream()
+ .filter((i) -> i != currentId)
+ .forEach((i) -> instanceMap.get(i).onMessage(leaderMessage));
+ return false;
+ }
+
+ /**
+ * Send heartbeat invoke message to the next instance.
+ *
+ * @param currentId Instance ID of which sends this message.
+ */
+ @Override
+ public void sendHeartbeatInvokeMessage(int currentId) {
+ var nextInstance = this.findNextInstance(currentId);
+ var heartbeatInvokeMessage = new Message(MessageType.HEARTBEAT_INVOKE, "");
+ nextInstance.onMessage(heartbeatInvokeMessage);
+ }
+
+ /**
+ * Find all the alive instances with smaller ID than current instance.
+ *
+ * @param currentId ID of current instance.
+ * @return ID list of all the candidate instance.
+ */
+ private List<Integer> findElectionCandidateInstanceList(int currentId) {
+ return instanceMap.keySet()
+ .stream()
+ .filter((i) -> i < currentId && instanceMap.get(i).isAlive())
+ .toList();
+ }
+
+}
+```
+
+```java
+public static void main(String[] args) {
+
+ Map<Integer, Instance> instanceMap = new HashMap<>();
+ var messageManager = new BullyMessageManager(instanceMap);
+
+ var instance1 = new BullyInstance(messageManager, 1, 1);
+ var instance2 = new BullyInstance(messageManager, 2, 1);
+ var instance3 = new BullyInstance(messageManager, 3, 1);
+ var instance4 = new BullyInstance(messageManager, 4, 1);
+ var instance5 = new BullyInstance(messageManager, 5, 1);
+
+ instanceMap.put(1, instance1);
+ instanceMap.put(2, instance2);
+ instanceMap.put(3, instance3);
+ instanceMap.put(4, instance4);
+ instanceMap.put(5, instance5);
+
+ instance4.onMessage(new Message(MessageType.HEARTBEAT_INVOKE, ""));
+
+ final var thread1 = new Thread(instance1);
+ final var thread2 = new Thread(instance2);
+ final var thread3 = new Thread(instance3);
+ final var thread4 = new Thread(instance4);
+ final var thread5 = new Thread(instance5);
+
+ thread1.start();
+ thread2.start();
+ thread3.start();
+ thread4.start();
+ thread5.start();
+
+ instance1.setAlive(false);
+ }
+```
+
+The console output
+```
+[Thread-3] INFO com.iluwatar.leaderelection.AbstractInstance - Instance 4 - Heartbeat Invoke Message handling...
+[Thread-3] INFO com.iluwatar.leaderelection.bully.BullyInstance - Instance 4- Leader is alive.
+[Thread-4] INFO com.iluwatar.leaderelection.AbstractInstance - Instance 5 - Heartbeat Invoke Message handling...
+[Thread-4] INFO com.iluwatar.leaderelection.bully.BullyInstance - Instance 5- Leader is not alive. Start election.
+[Thread-3] INFO com.iluwatar.leaderelection.AbstractInstance - Instance 4 - Election Invoke Message handling...
+[Thread-2] INFO com.iluwatar.leaderelection.AbstractInstance - Instance 3 - Election Invoke Message handling...
+[Thread-3] INFO com.iluwatar.leaderelection.bully.BullyInstance - Instance 4- Start election.
+[Thread-2] INFO com.iluwatar.leaderelection.bully.BullyInstance - Instance 3- Start election.
+[Thread-2] INFO com.iluwatar.leaderelection.AbstractInstance - Instance 3 - Election Invoke Message handling...
+[Thread-2] INFO com.iluwatar.leaderelection.bully.BullyInstance - Instance 3- Start election.
+[Thread-1] INFO com.iluwatar.leaderelection.AbstractInstance - Instance 2 - Election Invoke Message handling...
+[Thread-1] INFO com.iluwatar.leaderelection.bully.BullyInstance - Instance 2- Start election.
+[Thread-1] INFO com.iluwatar.leaderelection.bully.BullyInstance - Instance 2- Succeed in election. Start leader notification.
+[Thread-1] INFO com.iluwatar.leaderelection.AbstractInstance - Instance 2 - Election Invoke Message handling...
+[Thread-3] INFO com.iluwatar.leaderelection.AbstractInstance - Instance 4 - Leader Message handling...
+[Thread-2] INFO com.iluwatar.leaderelection.AbstractInstance - Instance 3 - Leader Message handling...
+[Thread-1] INFO com.iluwatar.leaderelection.AbstractInstance - Instance 2 - Election Invoke Message handling...
+[Thread-4] INFO com.iluwatar.leaderelection.AbstractInstance - Instance 5 - Leader Message handling...
+[Thread-0] INFO com.iluwatar.leaderelection.AbstractInstance - Instance 1 - Leader Message handling...
+[Thread-1] INFO com.iluwatar.leaderelection.AbstractInstance - Instance 2 - Election Invoke Message handling...
+[Thread-3] INFO com.iluwatar.leaderelection.bully.BullyInstance - Instance 4 - Leader update done.
+[Thread-2] INFO com.iluwatar.leaderelection.bully.BullyInstance - Instance 3 - Leader update done.
+[Thread-0] INFO com.iluwatar.leaderelection.bully.BullyInstance - Instance 1 - Leader update done.
+[Thread-4] INFO com.iluwatar.leaderelection.bully.BullyInstance - Instance 5 - Leader update done.
+[Thread-2] INFO com.iluwatar.leaderelection.AbstractInstance - Instance 3 - Heartbeat Invoke Message handling...
+[Thread-2] INFO com.iluwatar.leaderelection.bully.BullyInstance - Instance 3- Leader is alive.
+```
## Class diagram
![alt text](./etc/leader-election.urm.png "Leader Election pattern class diagram")
@@ -22,10 +836,7 @@ Do not use this pattern when
* there is a natural leader or dedicated process that can always act as the leader. For example, it may be possible to implement a singleton process that coordinates the task instances. If this process fails or becomes unhealthy, the system can shut it down and restart it.
* the coordination between tasks can be easily achieved by using a more lightweight mechanism. For example, if several task instances simply require coordinated access to a shared resource, a preferable solution might be to use optimistic or pessimistic locking to control access to that resource.
-## Real world examples
-
-* [Raft Leader Election](https://github.com/ronenhamias/raft-leader-election)
-
## Credits
* [Leader Election pattern](https://docs.microsoft.com/en-us/azure/architecture/patterns/leader-election)
+* [Raft Leader Election](https://github.com/ronenhamias/raft-leader-election)
| null | train | test | 2023-10-28T10:41:41 | "2022-10-29T19:59:39Z" | iluwatar | train |
iluwatar/java-design-patterns/2223_2771 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/2223 | iluwatar/java-design-patterns/2771 | [
"keyword_pr_to_issue"
] | 163c3017bb356937d876cd9a05905c012f3b0af6 | 83986c794bdd27755ab3504113eedd1fdac36f69 | [
"Could you please assign me?"
] | [] | "2023-11-06T03:57:50Z" | [
"type: feature",
"epic: documentation"
] | Explanation for Double Buffer | In this issue, let's add a proper explanation for the pattern.
Acceptance criteria
- The pattern's README.md has been amended with an explanation
- The explanation consists of
- Real world example
- In plain words
- Wikipedia says
- Programmatic example
| [
"double-buffer/README.md"
] | [
"double-buffer/README.md"
] | [] | diff --git a/double-buffer/README.md b/double-buffer/README.md
index 089e30e6d3d2..04b47ad97f7e 100644
--- a/double-buffer/README.md
+++ b/double-buffer/README.md
@@ -1,14 +1,243 @@
----
+---
title: Double Buffer
category: Behavioral
language: en
tag:
- Performance
- Game programming
----
+---
## Intent
-Double buffering is a term used to describe a device that has two buffers. The usage of multiple buffers increases the overall throughput of a device and helps prevents bottlenecks. This example shows using double buffer pattern on graphics. It is used to show one image or frame while a separate frame is being buffered to be shown next. This method makes animations and games look more realistic than the same done in a single buffer mode.
+Double buffering is a term used to describe a device that has two buffers. The usage of multiple
+buffers increases the overall throughput of a device and helps prevents bottlenecks. This example
+shows using double buffer pattern on graphics. It is used to show one image or frame while a separate
+frame is being buffered to be shown next. This method makes animations and games look more realistic
+than the same done in a single buffer mode.
+
+## Explanation
+
+Real world example
+> A typical example, and one that every game engine must address, is rendering. When the game draws
+> the world the users see, it does so one piece at a time -- the mountains in the distance,
+> the rolling hills, the trees, each in its turn. If the user watched the view draw incrementally
+> like that, the illusion of a coherent world would be shattered. The scene must update smoothly
+> and quickly, displaying a series of complete frames, each appearing instantly. Double buffering solves
+> the problem.
+
+In plain words
+> It ensures a state that is being rendered correctly while that state is modifying incrementally. It is
+> widely used in computer graphics.
+
+Wikipedia says
+> In computer science, multiple buffering is the use of more than one buffer to hold a block of data,
+> so that a "reader" will see a complete (though perhaps old) version of the data, rather than a
+> partially updated version of the data being created by a "writer". It is very commonly used for
+> computer display images.
+
+**Programmatic Example**
+
+Buffer interface that assures basic functionalities of a buffer.
+
+```java
+/**
+ * Buffer interface.
+ */
+public interface Buffer {
+
+ /**
+ * Clear the pixel in (x, y).
+ *
+ * @param x X coordinate
+ * @param y Y coordinate
+ */
+ void clear(int x, int y);
+
+ /**
+ * Draw the pixel in (x, y).
+ *
+ * @param x X coordinate
+ * @param y Y coordinate
+ */
+ void draw(int x, int y);
+
+ /**
+ * Clear all the pixels.
+ */
+ void clearAll();
+
+ /**
+ * Get all the pixels.
+ *
+ * @return pixel list
+ */
+ Pixel[] getPixels();
+
+}
+```
+
+One of the implementation of Buffer interface.
+```java
+/**
+ * FrameBuffer implementation class.
+ */
+public class FrameBuffer implements Buffer {
+
+ public static final int WIDTH = 10;
+ public static final int HEIGHT = 8;
+
+ private final Pixel[] pixels = new Pixel[WIDTH * HEIGHT];
+
+ public FrameBuffer() {
+ clearAll();
+ }
+
+ @Override
+ public void clear(int x, int y) {
+ pixels[getIndex(x, y)] = Pixel.WHITE;
+ }
+
+ @Override
+ public void draw(int x, int y) {
+ pixels[getIndex(x, y)] = Pixel.BLACK;
+ }
+
+ @Override
+ public void clearAll() {
+ Arrays.fill(pixels, Pixel.WHITE);
+ }
+
+ @Override
+ public Pixel[] getPixels() {
+ return pixels;
+ }
+
+ private int getIndex(int x, int y) {
+ return x + WIDTH * y;
+ }
+}
+```
+
+```java
+/**
+ * Pixel enum. Each pixel can be white (not drawn) or black (drawn).
+ */
+public enum Pixel {
+
+ WHITE,
+ BLACK;
+}
+```
+Scene represents the game scene where current buffer has already been rendered.
+```java
+/**
+ * Scene class. Render the output frame.
+ */
+@Slf4j
+public class Scene {
+
+ private final Buffer[] frameBuffers;
+
+ private int current;
+
+ private int next;
+
+ /**
+ * Constructor of Scene.
+ */
+ public Scene() {
+ frameBuffers = new FrameBuffer[2];
+ frameBuffers[0] = new FrameBuffer();
+ frameBuffers[1] = new FrameBuffer();
+ current = 0;
+ next = 1;
+ }
+
+ /**
+ * Draw the next frame.
+ *
+ * @param coordinateList list of pixels of which the color should be black
+ */
+ public void draw(List<? extends Pair<Integer, Integer>> coordinateList) {
+ LOGGER.info("Start drawing next frame");
+ LOGGER.info("Current buffer: " + current + " Next buffer: " + next);
+ frameBuffers[next].clearAll();
+ coordinateList.forEach(coordinate -> {
+ var x = coordinate.getKey();
+ var y = coordinate.getValue();
+ frameBuffers[next].draw(x, y);
+ });
+ LOGGER.info("Swap current and next buffer");
+ swap();
+ LOGGER.info("Finish swapping");
+ LOGGER.info("Current buffer: " + current + " Next buffer: " + next);
+ }
+
+ public Buffer getBuffer() {
+ LOGGER.info("Get current buffer: " + current);
+ return frameBuffers[current];
+ }
+
+ private void swap() {
+ current = current ^ next;
+ next = current ^ next;
+ current = current ^ next;
+ }
+
+}
+```
+
+```java
+public static void main(String[] args) {
+ final var scene = new Scene();
+ var drawPixels1 = List.of(
+ new MutablePair<>(1, 1),
+ new MutablePair<>(5, 6),
+ new MutablePair<>(3, 2)
+ );
+ scene.draw(drawPixels1);
+ var buffer1 = scene.getBuffer();
+ printBlackPixelCoordinate(buffer1);
+
+ var drawPixels2 = List.of(
+ new MutablePair<>(3, 7),
+ new MutablePair<>(6, 1)
+ );
+ scene.draw(drawPixels2);
+ var buffer2 = scene.getBuffer();
+ printBlackPixelCoordinate(buffer2);
+ }
+
+ private static void printBlackPixelCoordinate(Buffer buffer) {
+ StringBuilder log = new StringBuilder("Black Pixels: ");
+ var pixels = buffer.getPixels();
+ for (var i = 0; i < pixels.length; ++i) {
+ if (pixels[i] == Pixel.BLACK) {
+ var y = i / FrameBuffer.WIDTH;
+ var x = i % FrameBuffer.WIDTH;
+ log.append(" (").append(x).append(", ").append(y).append(")");
+ }
+ }
+ LOGGER.info(log.toString());
+ }
+```
+
+The console output
+```text
+[main] INFO com.iluwatar.doublebuffer.Scene - Start drawing next frame
+[main] INFO com.iluwatar.doublebuffer.Scene - Current buffer: 0 Next buffer: 1
+[main] INFO com.iluwatar.doublebuffer.Scene - Swap current and next buffer
+[main] INFO com.iluwatar.doublebuffer.Scene - Finish swapping
+[main] INFO com.iluwatar.doublebuffer.Scene - Current buffer: 1 Next buffer: 0
+[main] INFO com.iluwatar.doublebuffer.Scene - Get current buffer: 1
+[main] INFO com.iluwatar.doublebuffer.App - Black Pixels: (1, 1) (3, 2) (5, 6)
+[main] INFO com.iluwatar.doublebuffer.Scene - Start drawing next frame
+[main] INFO com.iluwatar.doublebuffer.Scene - Current buffer: 1 Next buffer: 0
+[main] INFO com.iluwatar.doublebuffer.Scene - Swap current and next buffer
+[main] INFO com.iluwatar.doublebuffer.Scene - Finish swapping
+[main] INFO com.iluwatar.doublebuffer.Scene - Current buffer: 0 Next buffer: 1
+[main] INFO com.iluwatar.doublebuffer.Scene - Get current buffer: 0
+[main] INFO com.iluwatar.doublebuffer.App - Black Pixels: (6, 1) (3, 7)
+```
## Class diagram
![alt text](./etc/double-buffer.urm.png "Double Buffer pattern class diagram")
| null | val | test | 2023-10-28T10:41:41 | "2022-10-29T19:58:54Z" | iluwatar | train |
iluwatar/java-design-patterns/2366_2776 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/2366 | iluwatar/java-design-patterns/2776 | [
"keyword_pr_to_issue"
] | 163c3017bb356937d876cd9a05905c012f3b0af6 | 0f39267a197e1e6ba08dfffa2d9df774fe25c6fe | [
"@iluwatar Can I work on this issue?\r\n",
"I would like to work on this issue, can I join?",
"This issue has been automatically marked as stale because it has not had recent activity. The issue will be unassigned if no further activity occurs. Thank you for your contributions.\n",
"Hello, I don't see any PR related to this problem. \r\nI still see both h2 db versions in the code, please assign this to me.",
"This issue has been automatically marked as stale because it has not had recent activity. The issue will be unassigned if no further activity occurs. Thank you for your contributions.\n"
] | [] | "2023-11-26T10:30:53Z" | [
"epic: architecture",
"type: refactoring",
"status: stale"
] | Uniform handling for H2 databases | At the moment, many of the patterns utilize H2 databases to demonstrate data access (search for `jdbc:h2`). The problem is that we don't have a unified approach. Some of the patterns use file-based database written somewhere under the home directory and some use in-memory databases. Perhaps we could use in-memory databases everywhere so the user's disk would not be cluttered? If not possible, at least store the database files under the same directory.
Acceptance criteria
- H2 database handling is unified
| [
"dao/src/main/java/com/iluwatar/dao/App.java",
"domain-model/src/main/java/com/iluwatar/domainmodel/App.java",
"layers/src/main/resources/application.properties",
"repository/src/main/java/com/iluwatar/repository/AppConfig.java",
"repository/src/main/resources/applicationContext.xml",
"serialized-entity/README.md",
"serialized-entity/src/main/java/com/iluwatar/serializedentity/App.java",
"table-module/src/main/java/com/iluwatar/tablemodule/App.java",
"transaction-script/src/main/java/com/iluwatar/transactionscript/App.java"
] | [
"dao/src/main/java/com/iluwatar/dao/App.java",
"domain-model/src/main/java/com/iluwatar/domainmodel/App.java",
"layers/src/main/resources/application.properties",
"repository/src/main/java/com/iluwatar/repository/AppConfig.java",
"repository/src/main/resources/applicationContext.xml",
"serialized-entity/README.md",
"serialized-entity/src/main/java/com/iluwatar/serializedentity/App.java",
"table-module/src/main/java/com/iluwatar/tablemodule/App.java",
"transaction-script/src/main/java/com/iluwatar/transactionscript/App.java"
] | [
"dao/src/test/java/com/iluwatar/dao/DbCustomerDaoTest.java",
"serialized-entity/src/test/java/com/iluwatar/serializedentity/AppTest.java",
"table-module/src/test/java/com/iluwatar/tablemodule/UserTableModuleTest.java",
"transaction-script/src/test/java/com/iluwatar/transactionscript/HotelDaoImplTest.java",
"transaction-script/src/test/java/com/iluwatar/transactionscript/HotelTest.java"
] | diff --git a/dao/src/main/java/com/iluwatar/dao/App.java b/dao/src/main/java/com/iluwatar/dao/App.java
index 20d1db0633dd..f0d19749c64b 100644
--- a/dao/src/main/java/com/iluwatar/dao/App.java
+++ b/dao/src/main/java/com/iluwatar/dao/App.java
@@ -44,7 +44,7 @@
*/
@Slf4j
public class App {
- private static final String DB_URL = "jdbc:h2:~/dao";
+ private static final String DB_URL = "jdbc:h2:mem:dao;DB_CLOSE_DELAY=-1";
private static final String ALL_CUSTOMERS = "customerDao.getAllCustomers(): ";
/**
diff --git a/domain-model/src/main/java/com/iluwatar/domainmodel/App.java b/domain-model/src/main/java/com/iluwatar/domainmodel/App.java
index 89c848f6696c..aade9924a400 100644
--- a/domain-model/src/main/java/com/iluwatar/domainmodel/App.java
+++ b/domain-model/src/main/java/com/iluwatar/domainmodel/App.java
@@ -49,7 +49,7 @@
*/
public class App {
- public static final String H2_DB_URL = "jdbc:h2:~/test";
+ public static final String H2_DB_URL = "jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1";
public static final String CREATE_SCHEMA_SQL =
"CREATE TABLE CUSTOMERS (name varchar primary key, money decimal);"
diff --git a/layers/src/main/resources/application.properties b/layers/src/main/resources/application.properties
index fad9b72a5ce7..233a9db6c8a5 100644
--- a/layers/src/main/resources/application.properties
+++ b/layers/src/main/resources/application.properties
@@ -2,7 +2,7 @@
spring.main.web-application-type=none
#datasource settings
-spring.datasource.url=jdbc:h2:~/databases/cake
+spring.datasource.url=jdbc:h2:mem:databases-cake
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=sa
diff --git a/repository/src/main/java/com/iluwatar/repository/AppConfig.java b/repository/src/main/java/com/iluwatar/repository/AppConfig.java
index ea93c21089e5..995c790b6e35 100644
--- a/repository/src/main/java/com/iluwatar/repository/AppConfig.java
+++ b/repository/src/main/java/com/iluwatar/repository/AppConfig.java
@@ -54,7 +54,7 @@ public class AppConfig {
public DataSource dataSource() {
var basicDataSource = new BasicDataSource();
basicDataSource.setDriverClassName("org.h2.Driver");
- basicDataSource.setUrl("jdbc:h2:~/databases/person");
+ basicDataSource.setUrl("jdbc:h2:mem:databases-person");
basicDataSource.setUsername("sa");
basicDataSource.setPassword("sa");
return basicDataSource;
diff --git a/repository/src/main/resources/applicationContext.xml b/repository/src/main/resources/applicationContext.xml
index 0de00f39f01d..718b6b6e6e13 100644
--- a/repository/src/main/resources/applicationContext.xml
+++ b/repository/src/main/resources/applicationContext.xml
@@ -30,7 +30,7 @@
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="org.h2.Driver" />
- <property name="url" value="jdbc:h2:~/databases/person" />
+ <property name="url" value="jdbc:h2:mem:databases-person;DB_CLOSE_DELAY=-1" />
<property name="username" value="sa" />
<property name="password" value="sa" />
</bean>
diff --git a/serialized-entity/README.md b/serialized-entity/README.md
index a994aa19cfbf..d18a2c83e9ad 100644
--- a/serialized-entity/README.md
+++ b/serialized-entity/README.md
@@ -136,7 +136,7 @@ methods to read and deserialize data items to `Country` objects.
```java
@Slf4j
public class App {
- private static final String DB_URL = "jdbc:h2:~/test";
+ private static final String DB_URL = "jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1";
private App() {
diff --git a/serialized-entity/src/main/java/com/iluwatar/serializedentity/App.java b/serialized-entity/src/main/java/com/iluwatar/serializedentity/App.java
index c86102a8231e..7f1f46905875 100644
--- a/serialized-entity/src/main/java/com/iluwatar/serializedentity/App.java
+++ b/serialized-entity/src/main/java/com/iluwatar/serializedentity/App.java
@@ -48,7 +48,7 @@
*/
@Slf4j
public class App {
- private static final String DB_URL = "jdbc:h2:~/test";
+ private static final String DB_URL = "jdbc:h2:mem:testdb";
private App() {
diff --git a/table-module/src/main/java/com/iluwatar/tablemodule/App.java b/table-module/src/main/java/com/iluwatar/tablemodule/App.java
index 632b4019dfa7..1c528df8a7f5 100644
--- a/table-module/src/main/java/com/iluwatar/tablemodule/App.java
+++ b/table-module/src/main/java/com/iluwatar/tablemodule/App.java
@@ -45,7 +45,7 @@
*/
@Slf4j
public final class App {
- private static final String DB_URL = "jdbc:h2:~/test";
+ private static final String DB_URL = "jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1";
/**
* Private constructor.
diff --git a/transaction-script/src/main/java/com/iluwatar/transactionscript/App.java b/transaction-script/src/main/java/com/iluwatar/transactionscript/App.java
index 0525e6e64a63..909943ce41d4 100644
--- a/transaction-script/src/main/java/com/iluwatar/transactionscript/App.java
+++ b/transaction-script/src/main/java/com/iluwatar/transactionscript/App.java
@@ -46,7 +46,7 @@
*/
public class App {
- private static final String H2_DB_URL = "jdbc:h2:~/test";
+ private static final String H2_DB_URL = "jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1";
private static final Logger LOGGER = LoggerFactory.getLogger(App.class);
/**
| diff --git a/dao/src/test/java/com/iluwatar/dao/DbCustomerDaoTest.java b/dao/src/test/java/com/iluwatar/dao/DbCustomerDaoTest.java
index 666c7634c158..cfa7e9882981 100644
--- a/dao/src/test/java/com/iluwatar/dao/DbCustomerDaoTest.java
+++ b/dao/src/test/java/com/iluwatar/dao/DbCustomerDaoTest.java
@@ -49,7 +49,7 @@
*/
class DbCustomerDaoTest {
- private static final String DB_URL = "jdbc:h2:~/dao";
+ private static final String DB_URL = "jdbc:h2:mem:dao;DB_CLOSE_DELAY=-1";
private DbCustomerDao dao;
private final Customer existingCustomer = new Customer(1, "Freddy", "Krueger");
diff --git a/serialized-entity/src/test/java/com/iluwatar/serializedentity/AppTest.java b/serialized-entity/src/test/java/com/iluwatar/serializedentity/AppTest.java
index 52ac9cd6e026..a15557d5ffdb 100644
--- a/serialized-entity/src/test/java/com/iluwatar/serializedentity/AppTest.java
+++ b/serialized-entity/src/test/java/com/iluwatar/serializedentity/AppTest.java
@@ -1,3 +1,27 @@
+/*
+ * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
+ *
+ * The MIT License
+ * Copyright © 2014-2022 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
package com.iluwatar.serializedentity;
import org.junit.jupiter.api.Test;
diff --git a/table-module/src/test/java/com/iluwatar/tablemodule/UserTableModuleTest.java b/table-module/src/test/java/com/iluwatar/tablemodule/UserTableModuleTest.java
index a9dc41b3e3f2..f45c20176700 100644
--- a/table-module/src/test/java/com/iluwatar/tablemodule/UserTableModuleTest.java
+++ b/table-module/src/test/java/com/iluwatar/tablemodule/UserTableModuleTest.java
@@ -36,7 +36,7 @@
import static org.junit.jupiter.api.Assertions.assertThrows;
class UserTableModuleTest {
- private static final String DB_URL = "jdbc:h2:~/test";
+ private static final String DB_URL = "jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1";
private static DataSource createDataSource() {
var dataSource = new JdbcDataSource();
diff --git a/transaction-script/src/test/java/com/iluwatar/transactionscript/HotelDaoImplTest.java b/transaction-script/src/test/java/com/iluwatar/transactionscript/HotelDaoImplTest.java
index ae288c703c1b..2f587397d873 100644
--- a/transaction-script/src/test/java/com/iluwatar/transactionscript/HotelDaoImplTest.java
+++ b/transaction-script/src/test/java/com/iluwatar/transactionscript/HotelDaoImplTest.java
@@ -49,7 +49,7 @@
*/
class HotelDaoImplTest {
- private static final String DB_URL = "jdbc:h2:~/test";
+ private static final String DB_URL = "jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1";
private HotelDaoImpl dao;
private Room existingRoom = new Room(1, "Single", 50, false);
diff --git a/transaction-script/src/test/java/com/iluwatar/transactionscript/HotelTest.java b/transaction-script/src/test/java/com/iluwatar/transactionscript/HotelTest.java
index 1274a542a77e..e8a7f6a0b8e4 100644
--- a/transaction-script/src/test/java/com/iluwatar/transactionscript/HotelTest.java
+++ b/transaction-script/src/test/java/com/iluwatar/transactionscript/HotelTest.java
@@ -39,7 +39,7 @@
*/
class HotelTest {
- private static final String H2_DB_URL = "jdbc:h2:~/test";
+ private static final String H2_DB_URL = "jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1";
private Hotel hotel;
private HotelDaoImpl dao;
| train | test | 2023-10-28T10:41:41 | "2022-11-29T19:07:58Z" | iluwatar | train |
iluwatar/java-design-patterns/1297_2818 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/1297 | iluwatar/java-design-patterns/2818 | [
"keyword_pr_to_issue"
] | e340f4f3f8c33efa63e10041b490516f3f892db5 | 98505c61dde1b91f730543fdf42c2ded9ee85630 | [
"Hi @iluwatar! can I work on this issue?",
"Please go ahead @kelumsampath ",
"Hello @iluwatar , I can work on this pattern if there are no takers :-)\r\n",
"All right, it's yours @shibicr93 ",
"This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.\n",
"Hi, I would like to help out. Could I work on this issue?",
"Could you review Pull Request https://github.com/iluwatar/java-design-patterns/pull/2734?\r\nI've implemented the gateway pattern based on my own interpretation. By the way, this is my first PR in an open-source project so I may need some advice and know where I can enhance my code.",
"This issue has been automatically marked as stale because it has not had recent activity. The issue will be unassigned if no further activity occurs. Thank you for your contributions.\n"
] | [] | "2024-03-10T09:03:54Z" | [
"epic: pattern",
"type: feature",
"status: stale"
] | Gateway pattern | https://stackoverflow.com/questions/4422211/what-is-the-difference-between-facade-and-gateway-design-patterns | [
"gateway/README.md",
"pom.xml"
] | [
"gateway/README.md",
"pom.xml"
] | [] | diff --git a/gateway/README.md b/gateway/README.md
index f1152ec6cfb4..9307b5d1d0f9 100644
--- a/gateway/README.md
+++ b/gateway/README.md
@@ -3,7 +3,6 @@ title: Gateway
category: Structural
language: en
tag:
-- Gang of Four
- Decoupling
---
@@ -38,7 +37,7 @@ The main class in our example is the `ExternalService` that contains items.
class ExternalServiceA implements Gateway {
@Override
public void execute() throws Exception {
- System.out.println("Executing Service A");
+ LOGGER.info("Executing Service A");
// Simulate a time-consuming task
Thread.sleep(1000);
}
@@ -50,7 +49,7 @@ class ExternalServiceA implements Gateway {
class ExternalServiceB implements Gateway {
@Override
public void execute() throws Exception {
- System.out.println("Executing Service B");
+ LOGGER.info("Executing Service B");
// Simulate a time-consuming task
Thread.sleep(1000);
}
@@ -62,7 +61,7 @@ class ExternalServiceB implements Gateway {
class ExternalServiceC implements Gateway {
@Override
public void execute() throws Exception {
- System.out.println("Executing Service C");
+ LOGGER.info("Executing Service C");
// Simulate a time-consuming task
Thread.sleep(1000);
}
@@ -100,7 +99,7 @@ public class App {
serviceB.execute();
serviceC.execute();
} catch (ThreadDeath e) {
- System.out.println("Interrupted!" + e);
+ LOGGER.info("Interrupted!" + e);
throw e;
}
}
diff --git a/pom.xml b/pom.xml
index 8af7ff7ae8a2..afa454245f25 100644
--- a/pom.xml
+++ b/pom.xml
@@ -212,6 +212,7 @@
<module>health-check</module>
<module>notification</module>
<module>single-table-inheritance</module>
+ <module>gateway</module>
</modules>
<repositories>
<repository>
| null | train | test | 2024-03-10T09:56:02 | "2020-07-07T17:36:34Z" | iluwatar | train |
iluwatar/java-design-patterns/2215_2875 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/2215 | iluwatar/java-design-patterns/2875 | [
"keyword_pr_to_issue"
] | 7c1889b8e5800b60013a96d567b64df51dd62ae1 | 9538c7820c34e879443078d9614fb570a00b4911 | [
"@iluwatar, I am interested to work on this issue.Will you assign this to me?",
"@iluwatar ,Can I know should I add about collection pipeline in existing folder, or should I create new folder and add the explanation ?",
"We need to provide a better explanation for the pattern in https://github.com/iluwatar/java-design-patterns/blob/master/collection-pipeline/README.md \r\n\r\nMore info in https://github.com/iluwatar/java-design-patterns/wiki/01.-How-to-contribute \r\n\r\nCheck out the other patterns for good examples",
"@iluwatar ,is there any guide related to the symbols used in the class diagram. So, that I can understand the classes better. At present, I felt difficulty when I am implementing the class diagram as example.",
"The class diagram is generated automatically from the code by [uml-reverse-mapper](https://github.com/iluwatar/uml-reverse-mapper) plugin",
"@iluwatar ,I notice the example suite to class diagram in the Collection Pipeline repo. I have a doubt ,should I include the example in the repo or I should create another example?",
"Ah, I see there is a class diagram generated with another plugin. I don't mind if you want to use the existing class diagram or generate a new one with uml-reverse-mapper. Both alternatives work.",
"This issue has been automatically marked as stale because it has not had recent activity. The issue will be unassigned if no further activity occurs. Thank you for your contributions.\n"
] | [] | "2024-03-30T11:21:24Z" | [
"type: feature",
"epic: documentation"
] | Explanation for Collection Pipeline | In this issue, let's add a proper explanation for the pattern.
Acceptance criteria
- The pattern's README.md has been amended with an explanation
- The explanation consists of
- Real world example
- In plain words
- Wikipedia says
- Programmatic example
| [
"collection-pipeline/README.md",
"collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/Car.java",
"collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/FunctionalProgramming.java",
"collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/ImperativeProgramming.java",
"collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/Person.java"
] | [
"collection-pipeline/README.md",
"collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/Car.java",
"collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/FunctionalProgramming.java",
"collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/ImperativeProgramming.java",
"collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/Person.java"
] | [] | diff --git a/collection-pipeline/README.md b/collection-pipeline/README.md
index 3ae285accb69..aab323e0ec14 100644
--- a/collection-pipeline/README.md
+++ b/collection-pipeline/README.md
@@ -3,25 +3,145 @@ title: Collection Pipeline
category: Functional
language: en
tag:
- - Reactive
+ - Reactive
+ - Data processing
---
## Intent
-Collection Pipeline introduces Function Composition and Collection Pipeline, two functional-style patterns that you can combine to iterate collections in your code.
-In functional programming, it's common to sequence complex operations through a series of smaller modular functions or operations. The series is called a composition of functions, or a function composition. When a collection of data flows through a function composition, it becomes a collection pipeline. Function Composition and Collection Pipeline are two design patterns frequently used in functional-style programming.
+
+The Collection Pipeline design pattern is intended to process collections of data by chaining together operations in a
+sequence where the output of one operation is the input for the next. It promotes a declarative approach to handling
+collections, focusing on what should be done rather than how.
+
+## Explanation
+
+Real-world example
+
+> Imagine you're in a large library filled with books, and you're tasked with finding all the science fiction books
+> published after 2000, then arranging them by author name in alphabetical order, and finally picking out the top 5 based
+> on their popularity or ratings.
+
+In plain words
+
+> The Collection Pipeline pattern involves processing data by passing it through a series of operations, each
+> transforming the data in sequence, much like an assembly line in a factory.
+
+Wikipedia says
+
+> In software engineering, a pipeline consists of a chain of processing elements (processes, threads, coroutines,
+> functions, etc.), arranged so that the output of each element is the input of the next; the name is by analogy to a
+> physical pipeline. Usually some amount of buffering is provided between consecutive elements. The information that flows
+> in these pipelines is often a stream of records, bytes, or bits, and the elements of a pipeline may be called filters;
+> this is also called the pipe(s) and filters design pattern. Connecting elements into a pipeline is analogous to function
+> composition.
+
+**Programmatic Example**
+
+The Collection Pipeline pattern is implemented in this code example by using Java's Stream API to perform a series of
+transformations on a collection of Car objects. The transformations are chained together to form a pipeline. Here's a
+breakdown of how it's done:
+
+1. Creation of Cars: A list of Car objects is created using the `CarFactory.createCars()` method.
+
+`var cars = CarFactory.createCars();`
+
+2. Filtering and Transforming: The `FunctionalProgramming.getModelsAfter2000(cars)` method filters the cars to only
+ include those made after the year 2000, and then transforms the filtered cars into a list of their model names.
+
+`var modelsFunctional = FunctionalProgramming.getModelsAfter2000(cars);`
+
+In the `getModelsAfter2000` method, the pipeline is created as follows:
+
+```java
+public static List<String> getModelsAfter2000(List<Car> cars){
+ return cars.stream().filter(car->car.getYear()>2000)
+ .sorted(comparing(Car::getYear))
+ .map(Car::getModel)
+ .collect(toList());
+ }
+```
+
+3. Grouping: The `FunctionalProgramming.getGroupingOfCarsByCategory(cars)` method groups the cars by their category.
+
+`var groupingByCategoryFunctional = FunctionalProgramming.getGroupingOfCarsByCategory(cars);`
+
+In the getGroupingOfCarsByCategory method, the pipeline is created as follows:
+
+```java
+public static Map<Category, List<Car>>getGroupingOfCarsByCategory(List<Car> cars){
+ return cars.stream().collect(groupingBy(Car::getCategory));
+ }
+```
+
+4. Filtering, Sorting and Transforming: The `FunctionalProgramming.getSedanCarsOwnedSortedByDate(List.of(john))` method
+ filters the cars owned by a person to only include sedans, sorts them by date, and then transforms the sorted cars
+ into a list of Car objects.
+
+`var sedansOwnedFunctional = FunctionalProgramming.getSedanCarsOwnedSortedByDate(List.of(john));`
+
+In the `getSedanCarsOwnedSortedByDate` method, the pipeline is created as follows:
+
+```java
+public static List<Car> getSedanCarsOwnedSortedByDate(List<Person> persons){
+ return persons.stream().flatMap(person->person.getCars().stream())
+ .filter(car->Category.SEDAN.equals(car.getCategory()))
+ .sorted(comparing(Car::getDate))
+ .collect(toList());
+ }
+```
+
+In each of these methods, the Collection Pipeline pattern is used to perform a series of operations on the collection of
+cars in a declarative manner, which improves readability and maintainability.
## Class diagram
+
![alt text](./etc/collection-pipeline.png "Collection Pipeline")
## Applicability
-Use the Collection Pipeline pattern when
-* When you want to perform a sequence of operations where one operation's collected output is fed into the next
-* When you use a lot of statements in your code
-* When you use a lot of loops in your code
+This pattern is applicable in scenarios involving bulk data operations such as filtering, mapping, sorting, or reducing
+collections. It's particularly useful in data analysis, transformation tasks, and where a sequence of operations needs
+to be applied to each element of a collection.
+
+## Known Uses
+
+* LINQ in .NET
+* Stream API in Java 8+
+* Collections in modern functional languages (e.g., Haskell, Scala)
+* Database query builders and ORM frameworks
+
+## Consequences
+
+Benefits:
+
+* Readability: The code is more readable and declarative, making it easier to understand the sequence of operations.
+* Maintainability: Easier to modify or extend the pipeline with additional operations.
+* Reusability: Common operations can be abstracted into reusable functions.
+* Lazy Evaluation: Some implementations allow for operations to be lazily evaluated, improving performance.
+
+Trade-offs:
+
+* Performance Overhead: Chaining multiple operations can introduce overhead compared to traditional loops, especially
+ for short pipelines or very large collections.
+* Debugging Difficulty: Debugging a chain of operations might be more challenging due to the lack of intermediate
+ variables.
+* Limited to Collections: Primarily focused on collections, and its utility might be limited outside of collection
+ processing.
+
+## Related Patterns
+
+* [Builder](https://java-design-patterns.com/patterns/builder/): Similar fluent interface style but used for object
+ construction.
+* [Chain of Responsibility](https://java-design-patterns.com/patterns/chain-of-responsibility/): Conceptually similar in
+ chaining handlers, but applied to object requests rather than data collection processing.
+* [Strategy](https://java-design-patterns.com/patterns/strategy/): Can be used within a pipeline stage to encapsulate
+ different algorithms that can be selected at runtime.
## Credits
* [Function composition and the Collection Pipeline pattern](https://www.ibm.com/developerworks/library/j-java8idioms2/index.html)
-* [Martin Fowler](https://martinfowler.com/articles/collection-pipeline/)
+* [Collection Pipeline described by Martin Fowler](https://martinfowler.com/articles/collection-pipeline/)
* [Java8 Streams](https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html)
+* [Refactoring: Improving the Design of Existing Code](https://amzn.to/3VDMWDO)
+* [Functional Programming in Scala](https://amzn.to/4cEo6K2)
+* [Java 8 in Action: Lambdas, Streams, and functional-style programming](https://amzn.to/3THp4wy)
diff --git a/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/Car.java b/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/Car.java
index 97e13231b24f..2cfeb963ba49 100644
--- a/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/Car.java
+++ b/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/Car.java
@@ -22,22 +22,11 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
-package com.iluwatar.collectionpipeline;
-import lombok.EqualsAndHashCode;
-import lombok.Getter;
-import lombok.RequiredArgsConstructor;
+package com.iluwatar.collectionpipeline;
/**
* A Car class that has the properties of make, model, year and category.
*/
-@Getter
-@EqualsAndHashCode
-@RequiredArgsConstructor
-public class Car {
- private final String make;
- private final String model;
- private final int year;
- private final Category category;
-
-}
\ No newline at end of file
+public record Car(String make, String model, int year, Category category) {
+}
diff --git a/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/FunctionalProgramming.java b/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/FunctionalProgramming.java
index adf0fda4bda2..20bf77d29a2f 100644
--- a/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/FunctionalProgramming.java
+++ b/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/FunctionalProgramming.java
@@ -22,6 +22,7 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
+
package com.iluwatar.collectionpipeline;
import java.util.Comparator;
@@ -54,9 +55,8 @@ private FunctionalProgramming() {
* @return {@link List} of {@link String} representing models built after year 2000
*/
public static List<String> getModelsAfter2000(List<Car> cars) {
- return cars.stream().filter(car -> car.getYear() > 2000)
- .sorted(Comparator.comparing(Car::getYear))
- .map(Car::getModel).toList();
+ return cars.stream().filter(car -> car.year() > 2000).sorted(Comparator.comparing(Car::year))
+ .map(Car::model).toList();
}
/**
@@ -66,7 +66,7 @@ public static List<String> getModelsAfter2000(List<Car> cars) {
* @return {@link Map} with category as key and cars belonging to that category as value
*/
public static Map<Category, List<Car>> getGroupingOfCarsByCategory(List<Car> cars) {
- return cars.stream().collect(Collectors.groupingBy(Car::getCategory));
+ return cars.stream().collect(Collectors.groupingBy(Car::category));
}
/**
@@ -76,8 +76,8 @@ public static Map<Category, List<Car>> getGroupingOfCarsByCategory(List<Car> car
* @return {@link List} of {@link Car} to belonging to the group
*/
public static List<Car> getSedanCarsOwnedSortedByDate(List<Person> persons) {
- return persons.stream().map(Person::getCars).flatMap(List::stream)
- .filter(car -> Category.SEDAN.equals(car.getCategory()))
- .sorted(Comparator.comparing(Car::getYear)).toList();
+ return persons.stream().map(Person::cars).flatMap(List::stream)
+ .filter(car -> Category.SEDAN.equals(car.category()))
+ .sorted(Comparator.comparing(Car::year)).toList();
}
}
diff --git a/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/ImperativeProgramming.java b/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/ImperativeProgramming.java
index e3359a389b0d..2a85334c6643 100644
--- a/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/ImperativeProgramming.java
+++ b/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/ImperativeProgramming.java
@@ -61,7 +61,7 @@ public static List<String> getModelsAfter2000(List<Car> cars) {
List<Car> carsSortedByYear = new ArrayList<>();
for (Car car : cars) {
- if (car.getYear() > 2000) {
+ if (car.year() > 2000) {
carsSortedByYear.add(car);
}
}
@@ -69,13 +69,13 @@ public static List<String> getModelsAfter2000(List<Car> cars) {
Collections.sort(carsSortedByYear, new Comparator<Car>() {
@Override
public int compare(Car car1, Car car2) {
- return car1.getYear() - car2.getYear();
+ return car1.year() - car2.year();
}
});
List<String> models = new ArrayList<>();
for (Car car : carsSortedByYear) {
- models.add(car.getModel());
+ models.add(car.model());
}
return models;
@@ -90,12 +90,12 @@ public int compare(Car car1, Car car2) {
public static Map<Category, List<Car>> getGroupingOfCarsByCategory(List<Car> cars) {
Map<Category, List<Car>> groupingByCategory = new HashMap<>();
for (Car car : cars) {
- if (groupingByCategory.containsKey(car.getCategory())) {
- groupingByCategory.get(car.getCategory()).add(car);
+ if (groupingByCategory.containsKey(car.category())) {
+ groupingByCategory.get(car.category()).add(car);
} else {
List<Car> categoryCars = new ArrayList<>();
categoryCars.add(car);
- groupingByCategory.put(car.getCategory(), categoryCars);
+ groupingByCategory.put(car.category(), categoryCars);
}
}
return groupingByCategory;
@@ -111,12 +111,12 @@ public static Map<Category, List<Car>> getGroupingOfCarsByCategory(List<Car> car
public static List<Car> getSedanCarsOwnedSortedByDate(List<Person> persons) {
List<Car> cars = new ArrayList<>();
for (Person person : persons) {
- cars.addAll(person.getCars());
+ cars.addAll(person.cars());
}
List<Car> sedanCars = new ArrayList<>();
for (Car car : cars) {
- if (Category.SEDAN.equals(car.getCategory())) {
+ if (Category.SEDAN.equals(car.category())) {
sedanCars.add(car);
}
}
@@ -124,7 +124,7 @@ public static List<Car> getSedanCarsOwnedSortedByDate(List<Person> persons) {
sedanCars.sort(new Comparator<Car>() {
@Override
public int compare(Car o1, Car o2) {
- return o1.getYear() - o2.getYear();
+ return o1.year() - o2.year();
}
});
diff --git a/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/Person.java b/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/Person.java
index 80b6a8bf0303..992596125423 100644
--- a/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/Person.java
+++ b/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/Person.java
@@ -25,16 +25,8 @@
package com.iluwatar.collectionpipeline;
import java.util.List;
-import lombok.Getter;
-import lombok.RequiredArgsConstructor;
/**
* A Person class that has the list of cars that the person owns and use.
*/
-@Getter
-@RequiredArgsConstructor
-public class Person {
-
- private final List<Car> cars;
-
-}
\ No newline at end of file
+public record Person(List<Car> cars) {}
| null | train | test | 2024-03-30T07:34:54 | "2022-10-29T19:58:23Z" | iluwatar | train |
iluwatar/java-design-patterns/2876_2877 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/2876 | iluwatar/java-design-patterns/2877 | [
"keyword_pr_to_issue"
] | 8471c93035b643528455cbba3957a0922d17e4de | 2228212c2361c3ed54babe2b3778f386f5aac9d5 | [] | [] | "2024-03-30T12:32:56Z" | [
"info: help wanted",
"type: feature",
"epic: documentation"
] | Explanation for Combinator pattern | In this issue, let's add a proper explanation for the pattern.
Acceptance criteria
- The pattern's README.md has been amended with an explanation
- The explanation consists of
- Real world example
- In plain words
- Wikipedia says
- Programmatic example | [
"combinator/README.md"
] | [
"combinator/README.md"
] | [
"combinator/src/test/java/com/iluwatar/combinator/FinderTest.java",
"combinator/src/test/java/com/iluwatar/combinator/FindersTest.java"
] | diff --git a/combinator/README.md b/combinator/README.md
index 15ec1ea59019..70b6a82f7942 100644
--- a/combinator/README.md
+++ b/combinator/README.md
@@ -1,132 +1,136 @@
---
title: Combinator
-category: Idiom
+category: Functional
language: en
tag:
- - Reactive
+ - Idiom
+ - Reactive
---
## Also known as
-Composition pattern
+* Function Composition
+* Functional Combinator
## Intent
-The functional pattern representing a style of organizing libraries centered around the idea of combining functions.
-Putting it simply, there is some type T, some functions for constructing “primitive” values of type T, and some “combinators” which can combine values of type T in various ways to build up more complex values of type T.
+The Combinator pattern is intended to enable complex functionalities by combining simple functions into more complex
+ones. It aims to achieve modularization and reusability by breaking down a task into simpler, interchangeable components
+that can be composed in various ways.
## Explanation
Real world example
-> In computer science, combinatory logic is used as a simplified model of computation, used in computability theory and proof theory. Despite its simplicity, combinatory logic captures many essential features of computation.
->
+> In computer science, combinatory logic is used as a simplified model of computation, used in computability theory and
+> proof theory. Despite its simplicity, combinatory logic captures many essential features of computation.
In plain words
-> The combinator allows you to create new "things" from previously defined "things".
->
+> The combinator allows you to create new "things" from previously defined "things"
Wikipedia says
-> A combinator is a higher-order function that uses only function application and earlier defined combinators to define a result from its arguments.
->
+> A combinator is a higher-order function that uses only function application and earlier defined combinators to define
+> a result from its arguments.
**Programmatic Example**
-Translating the combinator example above. First of all, we have a interface consist of several methods `contains`, `not`, `or`, `and` .
+Translating the combinator example above. First of all, we have an interface consist of several
+methods `contains`, `not`, `or`, `and` .
```java
// Functional interface to find lines in text.
public interface Finder {
- // The function to find lines in text.
- List<String> find(String text);
-
- // Simple implementation of function {@link #find(String)}.
- static Finder contains(String word) {
- return txt -> Stream.of(txt.split("\n"))
- .filter(line -> line.toLowerCase().contains(word.toLowerCase()))
- .collect(Collectors.toList());
- }
-
- // combinator not.
- default Finder not(Finder notFinder) {
- return txt -> {
- List<String> res = this.find(txt);
- res.removeAll(notFinder.find(txt));
- return res;
- };
- }
-
- // combinator or.
- default Finder or(Finder orFinder) {
- return txt -> {
- List<String> res = this.find(txt);
- res.addAll(orFinder.find(txt));
- return res;
- };
- }
-
- // combinator and.
- default Finder and(Finder andFinder) {
- return
- txt -> this
- .find(txt)
- .stream()
- .flatMap(line -> andFinder.find(line).stream())
- .collect(Collectors.toList());
- }
+ // The function to find lines in text.
+ List<String> find(String text);
+
+ // Simple implementation of function {@link #find(String)}.
+ static Finder contains(String word) {
+ return txt -> Stream.of(txt.split("\n"))
+ .filter(line -> line.toLowerCase().contains(word.toLowerCase()))
+ .collect(Collectors.toList());
+ }
+
+ // combinator not.
+ default Finder not(Finder notFinder) {
+ return txt -> {
+ List<String> res = this.find(txt);
+ res.removeAll(notFinder.find(txt));
+ return res;
+ };
+ }
+
+ // combinator or.
+ default Finder or(Finder orFinder) {
+ return txt -> {
+ List<String> res = this.find(txt);
+ res.addAll(orFinder.find(txt));
+ return res;
+ };
+ }
+
+ // combinator and.
+ default Finder and(Finder andFinder) {
+ return
+ txt -> this
+ .find(txt)
+ .stream()
+ .flatMap(line -> andFinder.find(line).stream())
+ .collect(Collectors.toList());
+ }
...
}
```
-Then we have also another combinator for some complex finders `advancedFinder`, `filteredFinder`, `specializedFinder` and `expandedFinder`.
+Then we have also another combinator for some complex finders `advancedFinder`, `filteredFinder`, `specializedFinder`
+and `expandedFinder`.
```java
// Complex finders consisting of simple finder.
public class Finders {
- private Finders() {
- }
-
- // Finder to find a complex query.
- public static Finder advancedFinder(String query, String orQuery, String notQuery) {
- return
- Finder.contains(query)
- .or(Finder.contains(orQuery))
- .not(Finder.contains(notQuery));
- }
-
- // Filtered finder looking a query with excluded queries as well.
- public static Finder filteredFinder(String query, String... excludeQueries) {
- var finder = Finder.contains(query);
-
- for (String q : excludeQueries) {
- finder = finder.not(Finder.contains(q));
- }
- return finder;
- }
-
- // Specialized query. Every next query is looked in previous result.
- public static Finder specializedFinder(String... queries) {
- var finder = identMult();
-
- for (String query : queries) {
- finder = finder.and(Finder.contains(query));
- }
- return finder;
- }
-
- // Expanded query. Looking for alternatives.
- public static Finder expandedFinder(String... queries) {
- var finder = identSum();
-
- for (String query : queries) {
- finder = finder.or(Finder.contains(query));
- }
- return finder;
- }
+ private Finders() {
+ }
+
+ // Finder to find a complex query.
+ public static Finder advancedFinder(String query, String orQuery, String notQuery) {
+ return
+ Finder.contains(query)
+ .or(Finder.contains(orQuery))
+ .not(Finder.contains(notQuery));
+ }
+
+ // Filtered finder looking a query with excluded queries as well.
+ public static Finder filteredFinder(String query, String... excludeQueries) {
+ var finder = Finder.contains(query);
+
+ for (String q : excludeQueries) {
+ finder = finder.not(Finder.contains(q));
+ }
+ return finder;
+ }
+
+ // Specialized query. Every next query is looked in previous result.
+ public static Finder specializedFinder(String... queries) {
+ var finder = identMult();
+
+ for (String query : queries) {
+ finder = finder.and(Finder.contains(query));
+ }
+ return finder;
+ }
+
+ // Expanded query. Looking for alternatives.
+ public static Finder expandedFinder(String... queries) {
+ var finder = identSum();
+
+ for (String query : queries) {
+ finder = finder.or(Finder.contains(query));
+ }
+ return finder;
+ }
...
}
```
@@ -134,75 +138,102 @@ public class Finders {
Now we have created the interface and methods for combinators. Now we have an application working on these combinators.
```java
-var queriesOr = new String[]{"many", "Annabel"};
-var finder = Finders.expandedFinder(queriesOr);
-var res = finder.find(text());
-LOGGER.info("the result of expanded(or) query[{}] is {}", queriesOr, res);
+var queriesOr=new String[]{"many","Annabel"};
+ var finder=Finders.expandedFinder(queriesOr);
+ var res=finder.find(text());
+ LOGGER.info("the result of expanded(or) query[{}] is {}",queriesOr,res);
-var queriesAnd = new String[]{"Annabel", "my"};
-finder = Finders.specializedFinder(queriesAnd);
-res = finder.find(text());
-LOGGER.info("the result of specialized(and) query[{}] is {}", queriesAnd, res);
+ var queriesAnd=new String[]{"Annabel","my"};
+ finder=Finders.specializedFinder(queriesAnd);
+ res=finder.find(text());
+ LOGGER.info("the result of specialized(and) query[{}] is {}",queriesAnd,res);
-finder = Finders.advancedFinder("it was", "kingdom", "sea");
-res = finder.find(text());
-LOGGER.info("the result of advanced query is {}", res);
+ finder=Finders.advancedFinder("it was","kingdom","sea");
+ res=finder.find(text());
+ LOGGER.info("the result of advanced query is {}",res);
-res = Finders.filteredFinder(" was ", "many", "child").find(text());
-LOGGER.info("the result of filtered query is {}", res);
+ res=Finders.filteredFinder(" was ","many","child").find(text());
+ LOGGER.info("the result of filtered query is {}",res);
-private static String text() {
- return
+private static String text(){
+ return
"It was many and many a year ago,\n"
- + "In a kingdom by the sea,\n"
- + "That a maiden there lived whom you may know\n"
- + "By the name of ANNABEL LEE;\n"
- + "And this maiden she lived with no other thought\n"
- + "Than to love and be loved by me.\n"
- + "I was a child and she was a child,\n"
- + "In this kingdom by the sea;\n"
- + "But we loved with a love that was more than love-\n"
- + "I and my Annabel Lee;\n"
- + "With a love that the winged seraphs of heaven\n"
- + "Coveted her and me.";
- }
+ +"In a kingdom by the sea,\n"
+ +"That a maiden there lived whom you may know\n"
+ +"By the name of ANNABEL LEE;\n"
+ +"And this maiden she lived with no other thought\n"
+ +"Than to love and be loved by me.\n"
+ +"I was a child and she was a child,\n"
+ +"In this kingdom by the sea;\n"
+ +"But we loved with a love that was more than love-\n"
+ +"I and my Annabel Lee;\n"
+ +"With a love that the winged seraphs of heaven\n"
+ +"Coveted her and me.";
+ }
```
**Program output:**
```java
-the result of expanded(or) query[[many, Annabel]] is [It was many and many a year ago,, By the name of ANNABEL LEE;, I and my Annabel Lee;]
-the result of specialized(and) query[[Annabel, my]] is [I and my Annabel Lee;]
-the result of advanced query is [It was many and many a year ago,]
-the result of filtered query is [But we loved with a love that was more than love-]
+the result of expanded(or)query[[many,Annabel]]is[It was many and many a year ago,,By the name of ANNABEL LEE;,I and my Annabel Lee;]
+ the result of specialized(and)query[[Annabel,my]]is[I and my Annabel Lee;]
+ the result of advanced query is[It was many and many a year ago,]
+ the result of filtered query is[But we loved with a love that was more than love-]
```
-Now we can design our app to with the queries finding feature `expandedFinder`, `specializedFinder`, `advancedFinder`, `filteredFinder` which are all derived from `contains`, `or`, `not`, `and`.
-
+Now we can design our app to with the queries finding
+feature `expandedFinder`, `specializedFinder`, `advancedFinder`, `filteredFinder` which are all derived
+from `contains`, `or`, `not`, `and`.
## Class diagram
+
![alt text](./etc/combinator.urm.png "Combinator class diagram")
## Applicability
-Use the combinator pattern when:
-- You are able to create a more complex value from more plain values but having the same type(a combination of them)
+This pattern is applicable in scenarios where:
+
+* The solution to a problem can be constructed from simple, reusable components.
+* There is a need for high modularity and reusability of functions.
+* The programming environment supports first-class functions and higher-order functions.
+
+## Known Uses
+
+* Functional programming languages like Haskell and Scala extensively use combinators for tasks ranging from parsing to
+ UI construction.
+* In domain-specific languages, particularly those involved in parsing, such as parsing expression grammars.
+* In libraries for functional programming in languages like JavaScript, Python, and Ruby.
+* java.util.function.Function#compose
+* java.util.function.Function#andThen
+
+## Consequences
+
+Benefits:
-## Benefits
+* Enhances modularity and reusability by breaking down complex tasks into simpler, composable functions.
+* Promotes readability and maintainability by using a declarative style of programming.
+* Facilitates lazy evaluation and potentially more efficient execution through function composition.
-- From a developers perspective the API is made of terms from the domain.
-- There is a clear distinction between combining and application phase.
-- One first constructs an instance and then executes it.
-- This makes the pattern applicable in a parallel environment.
+Trade-offs:
+* Can lead to a steep learning curve for those unfamiliar with functional programming principles.
+* May result in performance overhead due to the creation of intermediate functions.
+* Debugging can be challenging due to the abstract nature of function compositions.
-## Real world examples
+## Related Patterns
-- java.util.function.Function#compose
-- java.util.function.Function#andThen
+[Strategy](https://java-design-patterns.com/patterns/strategy/): Both involve selecting an algorithm at runtime, but
+Combinator uses composition of functions.
+[Decorator](https://java-design-patterns.com/patterns/decorator/): Similar to Combinator in enhancing functionality, but
+Decorator focuses on object augmentation.
+[Chain of Responsibility](https://java-design-patterns.com/patterns/chain-of-responsibility/): Relies on chaining
+objects, whereas Combinator chains functions.
## Credits
-- [Example for java](https://gtrefs.github.io/code/combinator-pattern/)
+- [Example for Java](https://gtrefs.github.io/code/combinator-pattern/)
- [Combinator pattern](https://wiki.haskell.org/Combinator_pattern)
- [Combinatory logic](https://wiki.haskell.org/Combinatory_logic)
+- [Structure and Interpretation of Computer Programs](https://amzn.to/3PJwVsf)
+- [Functional Programming in Scala](https://amzn.to/4cEo6K2)
+- [Haskell: The Craft of Functional Programming](https://amzn.to/4axxtcF)
| diff --git a/combinator/src/test/java/com/iluwatar/combinator/FinderTest.java b/combinator/src/test/java/com/iluwatar/combinator/FinderTest.java
index 4f0d42258d62..c4a505df075d 100644
--- a/combinator/src/test/java/com/iluwatar/combinator/FinderTest.java
+++ b/combinator/src/test/java/com/iluwatar/combinator/FinderTest.java
@@ -22,6 +22,7 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
+
package com.iluwatar.combinator;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -33,12 +34,12 @@ class FinderTest {
@Test
void contains() {
var example = """
- the first one
- the second one\s
- """;
+ the first one
+ the second one\s
+ """;
var result = Finder.contains("second").find(example);
assertEquals(1, result.size());
- assertEquals( "the second one ", result.get(0));
+ assertEquals("the second one ", result.get(0));
}
}
diff --git a/combinator/src/test/java/com/iluwatar/combinator/FindersTest.java b/combinator/src/test/java/com/iluwatar/combinator/FindersTest.java
index bf34af1704f7..aa84b9350d5b 100644
--- a/combinator/src/test/java/com/iluwatar/combinator/FindersTest.java
+++ b/combinator/src/test/java/com/iluwatar/combinator/FindersTest.java
@@ -22,6 +22,7 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
+
package com.iluwatar.combinator;
import static com.iluwatar.combinator.Finders.advancedFinder;
@@ -38,48 +39,47 @@ class FindersTest {
void advancedFinderTest() {
var res = advancedFinder("it was", "kingdom", "sea").find(text());
assertEquals(1, res.size());
- assertEquals( "It was many and many a year ago,", res.get(0));
+ assertEquals("It was many and many a year ago,", res.get(0));
}
@Test
void filteredFinderTest() {
var res = filteredFinder(" was ", "many", "child").find(text());
assertEquals(1, res.size());
- assertEquals( "But we loved with a love that was more than love-", res.get(0));
+ assertEquals("But we loved with a love that was more than love-", res.get(0));
}
@Test
void specializedFinderTest() {
var res = specializedFinder("love", "heaven").find(text());
assertEquals(1, res.size());
- assertEquals( "With a love that the winged seraphs of heaven", res.get(0));
+ assertEquals("With a love that the winged seraphs of heaven", res.get(0));
}
@Test
void expandedFinderTest() {
var res = expandedFinder("It was", "kingdom").find(text());
assertEquals(3, res.size());
- assertEquals( "It was many and many a year ago,", res.get(0));
- assertEquals( "In a kingdom by the sea,", res.get(1));
- assertEquals( "In this kingdom by the sea;", res.get(2));
+ assertEquals("It was many and many a year ago,", res.get(0));
+ assertEquals("In a kingdom by the sea,", res.get(1));
+ assertEquals("In this kingdom by the sea;", res.get(2));
}
private String text() {
- return
- """
- It was many and many a year ago,
- In a kingdom by the sea,
- That a maiden there lived whom you may know
- By the name of ANNABEL LEE;
- And this maiden she lived with no other thought
- Than to love and be loved by me.
- I was a child and she was a child,
- In this kingdom by the sea;
- But we loved with a love that was more than love-
- I and my Annabel Lee;
- With a love that the winged seraphs of heaven
- Coveted her and me.""";
+ return """
+ It was many and many a year ago,
+ In a kingdom by the sea,
+ That a maiden there lived whom you may know
+ By the name of ANNABEL LEE;
+ And this maiden she lived with no other thought
+ Than to love and be loved by me.
+ I was a child and she was a child,
+ In this kingdom by the sea;
+ But we loved with a love that was more than love-
+ I and my Annabel Lee;
+ With a love that the winged seraphs of heaven
+ Coveted her and me.""";
}
}
| train | test | 2024-03-30T12:58:18 | "2024-03-30T12:12:35Z" | iluwatar | train |
iluwatar/java-design-patterns/2216_2878 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/2216 | iluwatar/java-design-patterns/2878 | [
"keyword_pr_to_issue"
] | 2228212c2361c3ed54babe2b3778f386f5aac9d5 | 81ebcf0a791adb28175186332038922f5087c82d | [
"Could you please assign me? I want to nominate myself for this.",
"This issue has been automatically marked as stale because it has not had recent activity. The issue will be unassigned if no further activity occurs. Thank you for your contributions.\n"
] | [] | "2024-03-30T15:35:53Z" | [
"info: help wanted",
"type: feature",
"epic: documentation"
] | Explanation for Commander | In this issue, let's add a proper explanation for the pattern.
Acceptance criteria
- The pattern's README.md has been amended with an explanation
- The explanation consists of
- Real world example
- In plain words
- Wikipedia says
- Programmatic example
| [
"commander/README.md",
"commander/src/main/java/com/iluwatar/commander/Commander.java",
"commander/src/main/java/com/iluwatar/commander/Retry.java",
"commander/src/main/java/com/iluwatar/commander/employeehandle/EmployeeHandle.java",
"commander/src/main/java/com/iluwatar/commander/messagingservice/MessagingDatabase.java",
"commander/src/main/java/com/iluwatar/commander/messagingservice/MessagingService.java",
"commander/src/main/java/com/iluwatar/commander/paymentservice/PaymentService.java",
"commander/src/main/java/com/iluwatar/commander/queue/QueueDatabase.java"
] | [
"commander/README.md",
"commander/src/main/java/com/iluwatar/commander/Commander.java",
"commander/src/main/java/com/iluwatar/commander/Retry.java",
"commander/src/main/java/com/iluwatar/commander/employeehandle/EmployeeHandle.java",
"commander/src/main/java/com/iluwatar/commander/messagingservice/MessagingDatabase.java",
"commander/src/main/java/com/iluwatar/commander/messagingservice/MessagingService.java",
"commander/src/main/java/com/iluwatar/commander/paymentservice/PaymentService.java",
"commander/src/main/java/com/iluwatar/commander/queue/QueueDatabase.java"
] | [
"commander/src/test/java/com/iluwatar/commander/RetryTest.java"
] | diff --git a/commander/README.md b/commander/README.md
index 472370f4bbe1..f6cacd243f76 100644
--- a/commander/README.md
+++ b/commander/README.md
@@ -1,25 +1,162 @@
---
title: Commander
-category: Concurrency
+category: Behavioral
language: en
tag:
- - Cloud distributed
+ - Cloud distributed
+ - Microservices
+ - Transactions
---
+## Also known as
+
+* Distributed Transaction Commander
+* Transaction Coordinator
+
## Intent
-> Used to handle all problems that can be encountered when doing distributed transactions.
+The intent of the Commander pattern in the context of distributed transactions is to manage and coordinate complex
+transactions across multiple distributed components or services, ensuring consistency and integrity of the overall
+transaction. It encapsulates transaction commands and coordination logic, facilitating the implementation of distributed
+transaction protocols like two-phase commit or Saga.
+
+## Explanation
+
+Real-world example
+
+> Imagine organizing a large international music festival where various bands from around the world are scheduled to
+> perform. Each band's arrival, soundcheck, and performance are like individual transactions in a distributed system. The
+> festival organizer acts as the "Commander," coordinating these transactions to ensure that if a band's flight is
+> delayed (akin to a transaction failure), there's a backup plan, such as rescheduling or swapping time slots with another
+> band (compensating actions), to keep the overall schedule intact. This setup mirrors the Commander pattern in
+> distributed transactions, where various components must be coordinated to achieve a successful outcome despite
+> individual failures.
+
+In plain words
+
+> The Commander pattern turns a request into a stand-alone object, allowing for the parameterization of commands,
+> queueing of actions, and the implementation of undo operations.
+
+**Programmatic Example**
+
+Managing transactions across different services in a distributed system, such as an e-commerce platform with separate
+Payment and Shipping microservices, requires careful coordination to avoid issues. When a user places an order but one
+service (e.g., Payment) is unavailable while the other (e.g., Shipping) is ready, we need a robust solution to handle
+this discrepancy.
+
+A strategy to address this involves using a Commander component that orchestrates the process. Initially, the order is
+processed by the available service (Shipping in this case). The commander then attempts to synchronize the order with
+the currently unavailable service (Payment) by storing the order details in a database or queueing it for future
+processing. This queueing system must also account for possible failures in adding requests to the queue.
+
+The commander repeatedly tries to process the queued orders to ensure both services eventually reflect the same
+transaction data. This process involves ensuring idempotence, meaning that even if the same order synchronization
+request is made multiple times, it will only be executed once, preventing duplicate transactions. The goal is to achieve
+eventual consistency across services, where all systems are synchronized over time despite initial failures or delays.
+
+In the provided code, the Commander pattern is used to handle distributed transactions across multiple services (
+PaymentService, ShippingService, MessagingService, EmployeeHandle). Each service has its own database and can throw
+exceptions to simulate failures.
+
+The Commander class is the central part of this pattern. It takes instances of all services and their databases, along
+with some configuration parameters. The placeOrder method in the Commander class is used to place an order, which
+involves interacting with all the services.
+
+```java
+public class Commander {
+ // ... constructor and other methods ...
+
+ public void placeOrder(Order order) {
+ // ... implementation ...
+ }
+}
+```
+
+The User and Order classes represent a user and an order respectively. An order is placed by a user.
+
+```java
+public class User {
+ // ... constructor and other methods ...
+}
+
+public class Order {
+ // ... constructor and other methods ...
+}
+```
+
+Each service (e.g., PaymentService, ShippingService, MessagingService, EmployeeHandle) has its own database and can
+throw exceptions to simulate failures. For example, the PaymentService might throw a DatabaseUnavailableException if its
+database is unavailable.
+
+```java
+public class PaymentService {
+ // ... constructor and other methods ...
+}
+```
+
+The DatabaseUnavailableException, ItemUnavailableException, and ShippingNotPossibleException classes represent different
+types of exceptions that can occur.
+
+```java
+public class DatabaseUnavailableException extends Exception {
+ // ... constructor and other methods ...
+}
+
+public class ItemUnavailableException extends Exception {
+ // ... constructor and other methods ...
+}
+
+public class ShippingNotPossibleException extends Exception {
+ // ... constructor and other methods ...
+}
+```
+
+In the main method of each class (AppQueueFailCases, AppShippingFailCases), different scenarios are simulated by
+creating instances of the Commander class with different configurations and calling the placeOrder method.
## Class diagram
+
![alt text](./etc/commander.urm.png "Commander class diagram")
## Applicability
-This pattern can be used when we need to make commits into 2 (or more) databases to complete transaction, which cannot be done atomically and can thereby create problems.
-## Explanation
-Handling distributed transactions can be tricky, but if we choose to not handle it carefully, there could be unwanted consequences. Say, we have an e-commerce website which has a Payment microservice and a Shipping microservice. If the shipping is available currently but payment service is not up, or vice versa, how would we deal with it after having already received the order from the user?
-We need a mechanism in place which can handle these kinds of situations. We have to direct the order to either one of the services (in this example, shipping) and then add the order into the database of the other service (in this example, payment), since two databases cannot be updated atomically. If currently unable to do it, there should be a queue where this request can be queued, and there has to be a mechanism which allows for a failure in the queueing as well. All this needs to be done by constant retries while ensuring idempotence (even if the request is made several times, the change should only be applied once) by a commander class, to reach a state of eventual consistency.
+Use the Commander pattern for distributed transactions when:
+
+* You need to ensure data consistency across distributed services in the event of partial system failures.
+* Transactions span multiple microservices or distributed components requiring coordinated commit or rollback.
+* You are implementing long-lived transactions requiring compensating actions for rollback.
+
+## Known Uses
+
+* Two-Phase Commit (2PC) Protocols: Coordinating commit or rollback across distributed databases or services.
+* Saga Pattern Implementations: Managing long-lived business processes that span multiple microservices, with each step
+ having a compensating action for rollback.
+* Distributed Transactions in Microservices Architecture: Coordinating complex operations across microservices while
+ maintaining data integrity and consistency.
+
+## Consequences
+
+Benefits:
+
+* Provides a clear mechanism for managing complex distributed transactions, enhancing system reliability.
+* Enables the implementation of compensating transactions, which are crucial for maintaining consistency in long-lived
+ transactions.
+* Facilitates the integration of heterogeneous systems within a transactional context.
+
+Trade-offs:
+
+* Increases complexity, especially in failure scenarios, due to the need for coordinated rollback mechanisms.
+* Potentially impacts performance due to the overhead of coordination and consistency checks.
+* Saga-based implementations can lead to increased complexity in understanding the overall business process flow.
+
+## Related Patterns
+
+[Saga Pattern](https://java-design-patterns.com/patterns/saga/): Often discussed in tandem with the Commander pattern
+for distributed transactions, focusing on long-lived transactions with compensating actions.
## Credits
* [Distributed Transactions: The Icebergs of Microservices](https://www.grahamlea.com/2016/08/distributed-transactions-microservices-icebergs/)
+* [Microservices Patterns: With examples in Java](https://amzn.to/4axjnYW)
+* [Designing Data-Intensive Applications: The Big Ideas Behind Reliable, Scalable, and Maintainable Systems](https://amzn.to/4axHwOV)
+* [Enterprise Integration Patterns: Designing, Building, and Deploying Messaging Solutions](https://amzn.to/4aATcRe)
diff --git a/commander/src/main/java/com/iluwatar/commander/Commander.java b/commander/src/main/java/com/iluwatar/commander/Commander.java
index 6b6c90a03f8d..4a1483c11e02 100644
--- a/commander/src/main/java/com/iluwatar/commander/Commander.java
+++ b/commander/src/main/java/com/iluwatar/commander/Commander.java
@@ -121,7 +121,7 @@ void placeOrder(Order order) throws Exception {
sendShippingRequest(order);
}
- private void sendShippingRequest(Order order) throws Exception {
+ private void sendShippingRequest(Order order) {
var list = shippingService.exceptionsList;
Retry.Operation op = (l) -> {
if (!l.isEmpty()) {
@@ -233,7 +233,7 @@ private void sendPaymentRequest(Order order) {
try {
r.perform(list, order);
} catch (Exception e1) {
- e1.printStackTrace();
+ LOG.error("An exception occurred", e1);
}
});
t.start();
@@ -282,7 +282,7 @@ private void updateQueue(QueueTask qt) {
try {
r.perform(list, qt);
} catch (Exception e1) {
- e1.printStackTrace();
+ LOG.error("An exception occurred", e1);
}
});
t.start();
@@ -305,7 +305,7 @@ private void tryDoingTasksInQueue() { //commander controls operations done to qu
try {
r.perform(list, null);
} catch (Exception e1) {
- e1.printStackTrace();
+ LOG.error("An exception occurred", e1);
}
});
t2.start();
@@ -324,12 +324,12 @@ private void tryDequeue() {
};
Retry.HandleErrorIssue<QueueTask> handleError = (o, err) -> {
};
- var r = new Retry<QueueTask>(op, handleError, numOfRetries, retryDuration,
+ var r = new Retry<>(op, handleError, numOfRetries, retryDuration,
e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass()));
try {
r.perform(list, null);
} catch (Exception e1) {
- e1.printStackTrace();
+ LOG.error("An exception occurred", e1);
}
});
t3.start();
@@ -351,7 +351,7 @@ private void sendSuccessMessage(Order order) {
try {
r.perform(list, order);
} catch (Exception e1) {
- e1.printStackTrace();
+ LOG.error("An exception occurred", e1);
}
});
t.start();
@@ -409,7 +409,7 @@ private void sendPaymentFailureMessage(Order order) {
try {
r.perform(list, order);
} catch (Exception e1) {
- e1.printStackTrace();
+ LOG.error("An exception occurred", e1);
}
});
t.start();
@@ -465,7 +465,7 @@ private void sendPaymentPossibleErrorMsg(Order order) {
try {
r.perform(list, order);
} catch (Exception e1) {
- e1.printStackTrace();
+ LOG.error("An exception occurred", e1);
}
});
t.start();
@@ -537,7 +537,7 @@ private void employeeHandleIssue(Order order) {
try {
r.perform(list, order);
} catch (Exception e1) {
- e1.printStackTrace();
+ LOG.error("An exception occurred", e1);
}
});
t.start();
diff --git a/commander/src/main/java/com/iluwatar/commander/Retry.java b/commander/src/main/java/com/iluwatar/commander/Retry.java
index 45984dfaa910..71614668254b 100644
--- a/commander/src/main/java/com/iluwatar/commander/Retry.java
+++ b/commander/src/main/java/com/iluwatar/commander/Retry.java
@@ -94,7 +94,7 @@ public void perform(List<Exception> list, T obj) {
this.errors.add(e);
if (this.attempts.incrementAndGet() >= this.maxAttempts || !this.test.test(e)) {
this.handleError.handleIssue(obj, e);
- return; //return here...dont go further
+ return; //return here... don't go further
}
try {
long testDelay =
diff --git a/commander/src/main/java/com/iluwatar/commander/employeehandle/EmployeeHandle.java b/commander/src/main/java/com/iluwatar/commander/employeehandle/EmployeeHandle.java
index ac161fbb5404..441ce920feae 100644
--- a/commander/src/main/java/com/iluwatar/commander/employeehandle/EmployeeHandle.java
+++ b/commander/src/main/java/com/iluwatar/commander/employeehandle/EmployeeHandle.java
@@ -47,7 +47,7 @@ protected String updateDb(Object... parameters) throws DatabaseUnavailableExcept
var o = (Order) parameters[0];
if (database.get(o.id) == null) {
database.add(o);
- return o.id; //true rcvd - change addedToEmployeeHandle to true else dont do anything
+ return o.id; //true rcvd - change addedToEmployeeHandle to true else don't do anything
}
return null;
}
diff --git a/commander/src/main/java/com/iluwatar/commander/messagingservice/MessagingDatabase.java b/commander/src/main/java/com/iluwatar/commander/messagingservice/MessagingDatabase.java
index 7339a623c1ce..e4a000f1cf62 100644
--- a/commander/src/main/java/com/iluwatar/commander/messagingservice/MessagingDatabase.java
+++ b/commander/src/main/java/com/iluwatar/commander/messagingservice/MessagingDatabase.java
@@ -38,7 +38,7 @@ public class MessagingDatabase extends Database<MessageRequest> {
@Override
public MessageRequest add(MessageRequest r) {
- return data.put(r.reqId, r);
+ return data.put(r.reqId(), r);
}
@Override
diff --git a/commander/src/main/java/com/iluwatar/commander/messagingservice/MessagingService.java b/commander/src/main/java/com/iluwatar/commander/messagingservice/MessagingService.java
index 47d14b970b68..e00bde4997b6 100644
--- a/commander/src/main/java/com/iluwatar/commander/messagingservice/MessagingService.java
+++ b/commander/src/main/java/com/iluwatar/commander/messagingservice/MessagingService.java
@@ -44,11 +44,7 @@ enum MessageToSend {
PAYMENT_SUCCESSFUL
}
- @RequiredArgsConstructor
- static class MessageRequest {
- final String reqId;
- final MessageToSend msg;
- }
+ record MessageRequest(String reqId, MessageToSend msg) {}
public MessagingService(MessagingDatabase db, Exception... exc) {
super(db, exc);
diff --git a/commander/src/main/java/com/iluwatar/commander/paymentservice/PaymentService.java b/commander/src/main/java/com/iluwatar/commander/paymentservice/PaymentService.java
index 0ba0c531001f..28fda2eb2106 100644
--- a/commander/src/main/java/com/iluwatar/commander/paymentservice/PaymentService.java
+++ b/commander/src/main/java/com/iluwatar/commander/paymentservice/PaymentService.java
@@ -51,7 +51,7 @@ public PaymentService(PaymentDatabase db, Exception... exc) {
*/
public String receiveRequest(Object... parameters) throws DatabaseUnavailableException {
- //it could also be sending a userid, payment details here or something, not added here
+ //it could also be sending an userid, payment details here or something, not added here
var id = generateId();
var req = new PaymentRequest(id, (float) parameters[0]);
return updateDb(req);
diff --git a/commander/src/main/java/com/iluwatar/commander/queue/QueueDatabase.java b/commander/src/main/java/com/iluwatar/commander/queue/QueueDatabase.java
index 5f4f40b5b5df..b8189e6f0025 100644
--- a/commander/src/main/java/com/iluwatar/commander/queue/QueueDatabase.java
+++ b/commander/src/main/java/com/iluwatar/commander/queue/QueueDatabase.java
@@ -25,7 +25,6 @@
package com.iluwatar.commander.queue;
import com.iluwatar.commander.Database;
-import com.iluwatar.commander.exceptions.DatabaseUnavailableException;
import com.iluwatar.commander.exceptions.IsEmptyException;
import java.util.ArrayList;
import java.util.List;
| diff --git a/commander/src/test/java/com/iluwatar/commander/RetryTest.java b/commander/src/test/java/com/iluwatar/commander/RetryTest.java
index 2276b340efc7..c74fb94d0f9d 100644
--- a/commander/src/test/java/com/iluwatar/commander/RetryTest.java
+++ b/commander/src/test/java/com/iluwatar/commander/RetryTest.java
@@ -31,9 +31,13 @@
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
class RetryTest {
+ private static final Logger LOG = LoggerFactory.getLogger(RetryTest.class);
+
@Test
void performTest() {
Retry.Operation op = (l) -> {
@@ -53,16 +57,16 @@ void performTest() {
try {
r1.perform(arr1, order);
} catch (Exception e1) {
- e1.printStackTrace();
+ LOG.error("An exception occurred", e1);
}
var arr2 = new ArrayList<>(List.of(new DatabaseUnavailableException(), new ItemUnavailableException()));
try {
r2.perform(arr2, order);
} catch (Exception e1) {
- e1.printStackTrace();
+ LOG.error("An exception occurred", e1);
}
//r1 stops at ItemUnavailableException, r2 retries because it encounters DatabaseUnavailableException
- assertTrue(arr1.size() == 1 && arr2.size() == 0);
+ assertTrue(arr1.size() == 1 && arr2.isEmpty());
}
}
| val | test | 2024-03-30T13:44:43 | "2022-10-29T19:58:28Z" | iluwatar | train |
iluwatar/java-design-patterns/2870_2885 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/2870 | iluwatar/java-design-patterns/2885 | [
"keyword_pr_to_issue"
] | 74cce87c70385a629d3eb929c2767aec503ff0db | 9f97c1505d8985d7b0f6d4cea3f91c23a0b54bdd | [
"Hi @iluwatar ,\r\nUpgrading version of `jackson-databind` to 2.17.0 incompatible with current versions of `jackson-core` in the project which I have found 2.13.4 and 2.15.4. So we also have to upgrade the `jackson-core`.\r\nI have seen that only upgrading `jackson-databind` to 2.17.0 internally using 2.13.4.\r\n\r\n![jackson-1](https://github.com/iluwatar/java-design-patterns/assets/101238933/d2e7a3be-1088-40ea-be5f-abb12c57d519)\r\n\r\nSo I have added one extra dependency in project to upgrade the `jackson:core` to 2.17.0.\r\n\r\n![dynamic-proxy-dependency-list](https://github.com/iluwatar/java-design-patterns/assets/101238933/84a31efb-6cb5-41bb-bbdb-d438c2f30e34)\r\n\r\nAfter this all the testcase passed in `dynamic-proxy` and `event-sourcing`\r\n\r\n![dynamic-proxy-test-result](https://github.com/iluwatar/java-design-patterns/assets/101238933/fa196dde-aeed-4163-8bb0-6e6ef2c61d17)\r\n![event-sourcing-test-result](https://github.com/iluwatar/java-design-patterns/assets/101238933/262ebd70-9d39-4962-84aa-7a2526165832)\r\n",
"If this is acceptable then I can raise a pr.\r\ncc: @iluwatar ",
"Hey, sounds good @surjendu104 I'm looking forward to receiving the PR 👍🏻 ",
"Hi @iluwatar I have made the pr. ps review it. #2885 "
] | [] | "2024-04-01T15:14:46Z" | [
"info: good first issue",
"epic: dependencies"
] | Upgrade jackson-databind | The version bump of jackson-databind seems to need some work. See https://github.com/iluwatar/java-design-patterns/pull/2867
Acceptance criteria
- jackson-databind successfully upgraded to the latest version
| [
"dynamic-proxy/pom.xml",
"event-sourcing/pom.xml"
] | [
"dynamic-proxy/pom.xml",
"event-sourcing/pom.xml"
] | [] | diff --git a/dynamic-proxy/pom.xml b/dynamic-proxy/pom.xml
index 0ec69f0bcc6e..d308c7885993 100644
--- a/dynamic-proxy/pom.xml
+++ b/dynamic-proxy/pom.xml
@@ -35,10 +35,15 @@
</parent>
<artifactId>dynamic-proxy</artifactId>
<dependencies>
+ <dependency>
+ <groupId>com.fasterxml.jackson.core</groupId>
+ <artifactId>jackson-core</artifactId>
+ <version>2.17.0</version>
+ </dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
- <version>2.16.1</version>
+ <version>2.17.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
diff --git a/event-sourcing/pom.xml b/event-sourcing/pom.xml
index 569a5fceebd8..19f6feb8f7a7 100644
--- a/event-sourcing/pom.xml
+++ b/event-sourcing/pom.xml
@@ -39,9 +39,15 @@
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
+ <dependency>
+ <groupId>com.fasterxml.jackson.core</groupId>
+ <artifactId>jackson-core</artifactId>
+ <version>2.17.0</version>
+ </dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
+ <version>2.17.0</version>
</dependency>
</dependencies>
<build>
| null | train | test | 2024-04-01T16:54:49 | "2024-03-29T11:09:17Z" | iluwatar | train |
iluwatar/java-design-patterns/2853_2886 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/2853 | iluwatar/java-design-patterns/2886 | [
"keyword_pr_to_issue"
] | 74cce87c70385a629d3eb929c2767aec503ff0db | 3ac7cc326898429855246d2a9578cf59553b3153 | [
"assign it to me!! I resolved it locally",
"Hi @iluwatar I have made the pr. ps review it. #2886 "
] | [] | "2024-04-01T15:51:21Z" | [
"info: good first issue",
"type: refactoring"
] | Composite View refactoring needed | Servlets are components in Java web development, responsible for processing HTTP requests and generating responses. In this context, exceptions are used to handle and manage unexpected errors or exceptional conditions that may occur during the execution of a servlet.
Exceptions should not be thrown from servlet methods. These 4 hotspots need to be fixed:
AppServlet.java:64
AppServlet.java:71
AppServlet.java:81
AppServlet.java:90
Acceptance criteria
- The aforementioned exceptions have been caught properly | [
"composite-view/src/main/java/com/iluwatar/compositeview/AppServlet.java"
] | [
"composite-view/src/main/java/com/iluwatar/compositeview/AppServlet.java"
] | [] | diff --git a/composite-view/src/main/java/com/iluwatar/compositeview/AppServlet.java b/composite-view/src/main/java/com/iluwatar/compositeview/AppServlet.java
index 0cef25d2dd22..d2ec90675eb5 100644
--- a/composite-view/src/main/java/com/iluwatar/compositeview/AppServlet.java
+++ b/composite-view/src/main/java/com/iluwatar/compositeview/AppServlet.java
@@ -25,18 +25,17 @@
package com.iluwatar.compositeview;
import jakarta.servlet.RequestDispatcher;
-import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
-import java.io.IOException;
import java.io.PrintWriter;
+import lombok.extern.slf4j.Slf4j;
/**
* A servlet object that extends HttpServlet.
* Runs on Tomcat 10 and handles Http requests
*/
-
+@Slf4j
public final class AppServlet extends HttpServlet {
private static final String CONTENT_TYPE = "text/html";
private String msgPartOne = "<h1>This Server Doesn't Support";
@@ -56,39 +55,44 @@ public AppServlet() {
}
@Override
- public void doGet(HttpServletRequest req, HttpServletResponse resp)
- throws ServletException, IOException {
- RequestDispatcher requestDispatcher = req.getRequestDispatcher(destination);
- ClientPropertiesBean reqParams = new ClientPropertiesBean(req);
- req.setAttribute("properties", reqParams);
- requestDispatcher.forward(req, resp);
+ public void doGet(HttpServletRequest req, HttpServletResponse resp) {
+ try {
+ RequestDispatcher requestDispatcher = req.getRequestDispatcher(destination);
+ ClientPropertiesBean reqParams = new ClientPropertiesBean(req);
+ req.setAttribute("properties", reqParams);
+ requestDispatcher.forward(req, resp);
+ } catch (Exception e) {
+ LOGGER.error("Exception occurred GET request processing ", e);
+ }
}
@Override
- public void doPost(HttpServletRequest req, HttpServletResponse resp)
- throws ServletException, IOException {
+ public void doPost(HttpServletRequest req, HttpServletResponse resp) {
resp.setContentType(CONTENT_TYPE);
try (PrintWriter out = resp.getWriter()) {
out.println(msgPartOne + " Post " + msgPartTwo);
+ } catch (Exception e) {
+ LOGGER.error("Exception occurred POST request processing ", e);
}
-
}
@Override
- public void doDelete(HttpServletRequest req, HttpServletResponse resp)
- throws ServletException, IOException {
+ public void doDelete(HttpServletRequest req, HttpServletResponse resp) {
resp.setContentType(CONTENT_TYPE);
try (PrintWriter out = resp.getWriter()) {
out.println(msgPartOne + " Delete " + msgPartTwo);
+ } catch (Exception e) {
+ LOGGER.error("Exception occurred DELETE request processing ", e);
}
}
@Override
- public void doPut(HttpServletRequest req, HttpServletResponse resp)
- throws ServletException, IOException {
+ public void doPut(HttpServletRequest req, HttpServletResponse resp) {
resp.setContentType(CONTENT_TYPE);
try (PrintWriter out = resp.getWriter()) {
out.println(msgPartOne + " Put " + msgPartTwo);
+ } catch (Exception e) {
+ LOGGER.error("Exception occurred PUT request processing ", e);
}
}
}
| null | train | test | 2024-04-01T16:54:49 | "2024-03-27T14:38:51Z" | iluwatar | train |
iluwatar/java-design-patterns/2217_2896 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/2217 | iluwatar/java-design-patterns/2896 | [
"keyword_pr_to_issue"
] | 8f777cdc981877545194e513ac87f336f2e6fc00 | faac96b21b3074cc7196713ab029810b68db4961 | [
" I'm excited to contribute to this project, and I'd like to start by working on this issue as my first contribution. Could you please assign this issue to me? I would greatly appreciate it if you could provide some guidance on how to get started with addressing this issue. \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n",
"I've updated the pattern documentation in pull request #2590 with improvements. Please review it so that I can continue enhancing the documentation for other patterns.",
"This issue has been automatically marked as stale because it has not had recent activity. The issue will be unassigned if no further activity occurs. Thank you for your contributions.\n"
] | [] | "2024-04-06T09:56:49Z" | [
"type: feature",
"epic: documentation"
] | Explanation for Command Query Responsibility Segregation (CQRS) | In this issue, let's add a proper explanation for the pattern.
Acceptance criteria
- The pattern's README.md has been amended with an explanation
- The explanation consists of
- Real world example
- In plain words
- Wikipedia says
- Programmatic example
| [
"cqrs/README.md",
"cqrs/pom.xml"
] | [
"cqrs/README.md",
"cqrs/pom.xml"
] | [] | diff --git a/cqrs/README.md b/cqrs/README.md
index 6ac6061ef70e..e4af36bc3c51 100644
--- a/cqrs/README.md
+++ b/cqrs/README.md
@@ -3,25 +3,89 @@ title: CQRS
category: Architectural
language: en
tag:
- - Performance
- - Cloud distributed
+ - Event-driven
+ - Performance
+ - Scalability
---
## Intent
-CQRS Command Query Responsibility Segregation - Separate the query side from the command side.
+
+CQRS aims to segregate the operations that modify the state of an application (commands) from the operations that read the state (queries). This separation allows for more flexible and optimized designs, especially in complex systems.
+
+## Explanation
+
+Real world example
+
+> Imagine a modern library where the tasks of borrowing and returning books (commands) are handled at the front desk, while the task of searching for books and reading them (queries) happens in the reading area. The front desk optimizes for transaction efficiency and record-keeping, ensuring books are properly checked in and out. Meanwhile, the reading area is optimized for comfort and accessibility, making it easy for readers to find and engage with the books. This separation improves the library's overall efficiency and user experience, much like the CQRS pattern enhances a software system's performance and maintainability.
+
+In plain words
+
+> The CQRS design pattern separates the actions of modifying data (commands) from the actions of retrieving data (queries) to enhance performance, scalability, and maintainability in software systems.
+
+**Programmatic Example**
+
+One way to implement the Command Query Responsibility Segregation (CQRS) pattern is to separate the read and write operations into different services.
+
+1. Command Service: The `CommandServiceImpl` class is used for write operations. It provides methods to create authors and books, and to add books to authors. Here's a snippet of how it's used:
+
+```java
+var commands=new CommandServiceImpl();
+ commands.authorCreated(AppConstants.E_EVANS,"Eric Evans","evans@email.com");
+ commands.bookAddedToAuthor("Domain-Driven Design",60.08,AppConstants.E_EVANS);
+```
+
+2. Query Service: The `QueryServiceImpl` class is used for read operations. It provides methods to get author and book details. Here's a snippet of how it's used:
+
+```java
+var queries=new QueryServiceImpl();
+ var evans=queries.getAuthorByUsername(AppConstants.E_EVANS);
+ var dddBook=queries.getBook("Domain-Driven Design");
+```
+
+This separation of concerns allows for flexibility in how the application handles data access and manipulation, and is a key aspect of the CQRS pattern.
## Class diagram
+
![alt text](./etc/cqrs.png "CQRS")
## Applicability
-Use the CQRS pattern when
-* You want to scale the queries and commands independently.
-* You want to use different data models for queries and commands. Useful when dealing with complex domains.
-* You want to use architectures like event sourcing or task based UI.
+* Systems requiring distinct models for read and write operations for scalability and maintainability.
+* Complex domain models where the task of updating objects differs significantly from the task of reading object data.
+* Scenarios where performance optimization for read operations is crucial, and the system can benefit from different data models or databases for reads and writes.
+
+## Known Uses
+
+* Distributed Systems and Microservices Architecture, where different services manage read and write responsibilities.
+* Event-Sourced Systems, where changes to the application state are stored as a sequence of events.
+* High-Performance Web Applications, segregating read and write databases to optimize load handling.
+
+## Consequences
+
+Benefits:
+
+* Scalability: By separating read and write models, each can be scaled independently according to their specific demands.
+* Optimization: Allows for the optimization of read models for query efficiency and write models for transactional integrity.
+* Maintainability: Reduces complexity by separating the concerns, leading to cleaner, more maintainable code.
+* Flexibility: Offers the flexibility to choose different technologies for the read and write sides according to their requirements.
+
+Trade-Offs:
+
+* Complexity: Introduces complexity due to synchronization between read and write models, especially in consistency maintenance.
+* Overhead: Might be an overkill for simple systems where the benefits do not outweigh the additional complexity.
+* Learning Curve: Requires a deeper understanding and careful design to implement effectively, increasing the initial learning curve.
+
+## Related Patterns
+
+* [Event Sourcing](https://java-design-patterns.com/patterns/event-sourcing/): Often used in conjunction with CQRS, where changes to the application state are stored as a sequence of events.
+* Domain-Driven Design (DDD): CQRS fits well within the DDD context, providing clear boundaries and separation of concerns.
+* [Repository](https://java-design-patterns.com/patterns/repository/): Can be used to abstract the data layer, providing a more seamless integration between the command and query sides.
## Credits
+* [Patterns, Principles, and Practices of Domain-Driven Design](https://amzn.to/3vNV4Hm)
+* [Implementing Domain-Driven Design](https://amzn.to/3TJN2HH)
+* [Microsoft .NET: Architecting Applications for the Enterprise](https://amzn.to/4aktRes)
* [Greg Young - CQRS, Task Based UIs, Event Sourcing agh!](http://codebetter.com/gregyoung/2010/02/16/cqrs-task-based-uis-event-sourcing-agh/)
* [Martin Fowler - CQRS](https://martinfowler.com/bliki/CQRS.html)
* [Oliver Wolf - CQRS for Great Good](https://www.youtube.com/watch?v=Ge53swja9Dw)
diff --git a/cqrs/pom.xml b/cqrs/pom.xml
index 58ad7f29a62c..ec78265cff66 100644
--- a/cqrs/pom.xml
+++ b/cqrs/pom.xml
@@ -26,55 +26,53 @@
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <parent>
- <groupId>com.iluwatar</groupId>
- <artifactId>java-design-patterns</artifactId>
- <version>1.26.0-SNAPSHOT</version>
- </parent>
- <artifactId>cqrs</artifactId>
- <dependencies>
- <dependency>
- <groupId>org.junit.jupiter</groupId>
- <artifactId>junit-jupiter-engine</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>com.h2database</groupId>
- <artifactId>h2</artifactId>
- </dependency>
- <dependency>
- <groupId>org.hibernate</groupId>
- <artifactId>hibernate-core</artifactId>
- </dependency>
- <dependency>
- <groupId>org.glassfish.jaxb</groupId>
- <artifactId>jaxb-runtime</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>javax.xml.bind</groupId>
- <artifactId>jaxb-api</artifactId>
- <scope>test</scope>
- </dependency>
- </dependencies>
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-assembly-plugin</artifactId>
- <executions>
- <execution>
- <configuration>
- <archive>
- <manifest>
- <mainClass>com.iluwatar.cqrs.app.App</mainClass>
- </manifest>
- </archive>
- </configuration>
- </execution>
- </executions>
- </plugin>
- </plugins>
- </build>
+ <modelVersion>4.0.0</modelVersion>
+ <parent>
+ <groupId>com.iluwatar</groupId>
+ <artifactId>java-design-patterns</artifactId>
+ <version>1.26.0-SNAPSHOT</version>
+ </parent>
+ <artifactId>cqrs</artifactId>
+ <dependencies>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-engine</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>com.h2database</groupId>
+ <artifactId>h2</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.hibernate</groupId>
+ <artifactId>hibernate-core</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.glassfish.jaxb</groupId>
+ <artifactId>jaxb-runtime</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>javax.xml.bind</groupId>
+ <artifactId>jaxb-api</artifactId>
+ </dependency>
+ </dependencies>
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-assembly-plugin</artifactId>
+ <executions>
+ <execution>
+ <configuration>
+ <archive>
+ <manifest>
+ <mainClass>com.iluwatar.cqrs.app.App</mainClass>
+ </manifest>
+ </archive>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ </plugins>
+ </build>
</project>
| null | test | test | 2024-04-06T09:43:40 | "2022-10-29T19:58:33Z" | iluwatar | train |
iluwatar/java-design-patterns/2219_2899 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/2219 | iluwatar/java-design-patterns/2899 | [
"keyword_pr_to_issue"
] | 356ba272720da7eb9cf3d622a4768c0957fa0e87 | ea55eb4e58dc7c0b3517dfb92c3a9b7cec1f6954 | [
"@iluwatar I can try this as well!",
"This issue has been automatically marked as stale because it has not had recent activity. The issue will be unassigned if no further activity occurs. Thank you for your contributions.\n"
] | [] | "2024-04-07T09:14:40Z" | [
"type: feature",
"epic: documentation"
] | Explanation for Data Locality | In this issue, let's add a proper explanation for the pattern.
Acceptance criteria
- The pattern's README.md has been amended with an explanation
- The explanation consists of
- Real world example
- In plain words
- Wikipedia says
- Programmatic example
| [
"data-locality/README.md"
] | [
"data-locality/README.md"
] | [
"data-locality/src/test/java/com/iluwatar/data/locality/ApplicationTest.java"
] | diff --git a/data-locality/README.md b/data-locality/README.md
index 212bd663a08d..c44ba1a34fa5 100644
--- a/data-locality/README.md
+++ b/data-locality/README.md
@@ -1,29 +1,135 @@
---
title: Data Locality
-category: Behavioral
+category: Performance optimization
language: en
tag:
- - Game programming
- - Performance
+ - Caching
+ - Data access
+ - Game programming
+ - Memory management
+ - Performance
---
+## Also known as
+
+* Cache-Friendly Design
+* Data-Oriented Design
+
## Intent
-Accelerate memory access by arranging data to take advantage of CPU caching.
-Modern CPUs have caches to speed up memory access. These can access memory adjacent to recently accessed memory much quicker. Take advantage of that to improve performance by increasing data locality keeping data in contiguous memory in the order that you process it.
+The Data Locality design pattern aims to minimize data access times and improve cache utilization by arranging data in memory to take advantage of spatial locality. This pattern is particularly useful in high-performance computing and game development where access speed is crucial.
+
+## Explanation
+
+Real-world example
+
+> Consider a supermarket where items are arranged based on purchase patterns and categories for efficiency. Just like the Data Locality pattern organizes data in memory for quick access, the supermarket places frequently bought items together and in easily accessible areas. This layout minimizes the time shoppers spend searching for items, enhancing their shopping experience by ensuring that related and popular items are close at hand, much like how data locality improves cache utilization and reduces access latency in computing.
+
+In plain words
+
+> The Data Locality pattern organizes data in memory to reduce access times and improve performance by ensuring that data frequently accessed together is stored close together.
+
+Programmatic Example
+
+The Data Locality pattern is a design pattern that aims to improve performance by arranging data in memory to take advantage of spatial locality. This pattern is particularly useful in high-performance computing and game development where access speed is crucial.
+
+In the data-locality module, the pattern is demonstrated using a game loop that processes a bunch of game entities. These entities are decomposed into different domains: AI, physics, and rendering.
+
+The GameEntity class is the main class that represents a game entity. It contains an array of AiComponent, PhysicsComponent, and RenderComponent objects. These components represent different aspects of a game entity.
+
+```java
+public class GameEntity {
+ private final AiComponent[] aiComponents;
+ private final PhysicsComponent[] physicsComponents;
+ private final RenderComponent[] renderComponents;
+// ...
+}
+```
+
+The GameEntity class has a start method that initializes all the components.
+
+```java
+public void start() {
+ for (int i = 0; i < numEntities; i++) {
+ aiComponents[i] = new AiComponent();
+ physicsComponents[i] = new PhysicsComponent();
+ renderComponents[i] = new RenderComponent();
+ }
+}
+```
+
+The GameEntity class also has an update method that updates all the components. This method demonstrates the data locality pattern. Instead of updating all aspects of a single entity at a time (AI, physics, and rendering), it updates the same aspect (e.g., AI) for all entities first, then moves on to the next aspect (e.g., physics). This approach improves cache utilization because it's more likely that the data needed for the update is already in the cache.
+
+```java
+public void update() {
+ for (int i = 0; i < numEntities; i++) {
+ aiComponents[i].update();
+ }
+ for (int i = 0; i < numEntities; i++) {
+ physicsComponents[i].update();
+ }
+ for (int i = 0; i < numEntities; i++) {
+ renderComponents[i].update();
+ }
+}
+```
+
+The Application class contains the main method that creates a GameEntity object and starts the game loop.
+
+```java
+public class Application {
+ public static void main(String[] args) {
+ var gameEntity = new GameEntity(NUM_ENTITIES);
+ gameEntity.start();
+ gameEntity.update();
+ }
+}
+```
+
+In this way, the data-locality module demonstrates the Data Locality pattern. By updating all components of the same type together, it increases the likelihood that the data needed for the update is already in the cache, thereby improving performance.
## Class diagram
+
![alt text](./etc/data-locality.urm.png "Data Locality pattern class diagram")
## Applicability
-* Like most optimizations, the first guideline for using the Data Locality pattern is when you have a performance problem.
-* With this pattern specifically, you’ll also want to be sure your performance problems are caused by cache misses.
+This pattern is applicable in scenarios where large datasets are processed and performance is critical. It's particularly useful in:
+
+* Game development for efficient rendering and physics calculations.
+* High-performance computing tasks that require rapid access to large data sets.
+* Real-time data processing systems where latency is a critical factor.
+
+## Known Uses
+
+* Game engines (e.g., Unity, Unreal Engine) to optimize entity and component data access.
+* High-performance matrix libraries in scientific computing to optimize matrix operations.
+* Real-time streaming data processing systems for efficient data manipulation and access.
+
+## Consequences
+
+Benefits:
+
+* Improved Cache Utilization: By enhancing spatial locality, data frequently accessed together is stored close together in memory, improving cache hit rates.
+* Reduced Access Latency: Minimizes the time taken to fetch data from memory, leading to performance improvements.
+* Enhanced Performance: Overall system performance is improved due to reduced memory access times and increased efficiency in data processing.
+
+Trade-offs:
+
+* Complexity in Implementation: Managing data layout can add complexity to the system design and implementation.
+* Maintenance Overhead: As data access patterns evolve, the layout may need to be re-evaluated, adding to the maintenance overhead.
+* Less Flexibility: The tight coupling of data layout to access patterns can reduce flexibility in how data structures are used and evolved over time.
-## Real world example
+## Related Patterns
-* The [Artemis](http://gamadu.com/artemis/) game engine is one of the first and better-known frameworks that uses simple IDs for game entities.
+* [Flyweight](https://java-design-patterns.com/patterns/flyweight/): Can be used in conjunction with Data Locality to share data efficiently among multiple objects.
+* [Object Pool](https://java-design-patterns.com/patterns/object-pool/): Often used together to manage a group of initialized objects that can be reused, further optimizing memory usage and access.
+* [Iterator](https://java-design-patterns.com/patterns/iterator/): Facilitates navigation through a collection of data laid out with data locality in mind.
## Credits
-* [Game Programming Patterns Optimization Patterns: Data Locality](http://gameprogrammingpatterns.com/data-locality.html)
\ No newline at end of file
+* [Game Programming Patterns](https://amzn.to/3vK8c0d)
+* [High-Performance Java Persistence](https://amzn.to/3TMc8Wd)
+* [Java Performance: The Definitive Guide](https://amzn.to/3Ua392J)
+* [Effective Java](https://amzn.to/4cGk2Jz)
+* [Game Programming Patterns Optimization Patterns: Data Locality](http://gameprogrammingpatterns.com/data-locality.html)
| diff --git a/data-locality/src/test/java/com/iluwatar/data/locality/ApplicationTest.java b/data-locality/src/test/java/com/iluwatar/data/locality/ApplicationTest.java
index 1f5986c9f2bc..1f1689425f41 100644
--- a/data-locality/src/test/java/com/iluwatar/data/locality/ApplicationTest.java
+++ b/data-locality/src/test/java/com/iluwatar/data/locality/ApplicationTest.java
@@ -36,7 +36,6 @@ class ApplicationTest {
/**
* Issue: Add at least one assertion to this test case.
- *
* Solution: Inserted assertion to check whether the execution of the main method in {@link Application#main(String[])}
* throws an exception.
*/
| train | test | 2024-04-07T10:29:35 | "2022-10-29T19:58:41Z" | iluwatar | train |
iluwatar/java-design-patterns/2220_2900 | iluwatar/java-design-patterns | iluwatar/java-design-patterns/2220 | iluwatar/java-design-patterns/2900 | [
"keyword_pr_to_issue"
] | ea55eb4e58dc7c0b3517dfb92c3a9b7cec1f6954 | 39acd1d0fb3ba2d70acde009de52bfd3d356e189 | [
"Hi, I want to take this issue(I have taken this issue before but was closed)",
"Sorry to bother you, but I accidentally removed myself as the issue assignee, can you assign this issue to me again. Thank you so much!"
] | [] | "2024-04-07T10:58:48Z" | [
"type: feature",
"epic: documentation"
] | Explanation for Data Mapper | In this issue, let's add a proper explanation for the pattern.
Acceptance criteria
- The pattern's README.md has been amended with an explanation
- The explanation consists of
- Real world example
- In plain words
- Wikipedia says
- Programmatic example
| [
"data-mapper/README.md",
"data-mapper/src/main/java/com/iluwatar/datamapper/DataMapperException.java",
"data-mapper/src/main/java/com/iluwatar/datamapper/Student.java",
"data-mapper/src/main/java/com/iluwatar/datamapper/StudentDataMapperImpl.java"
] | [
"data-mapper/README.md",
"data-mapper/src/main/java/com/iluwatar/datamapper/DataMapperException.java",
"data-mapper/src/main/java/com/iluwatar/datamapper/Student.java",
"data-mapper/src/main/java/com/iluwatar/datamapper/StudentDataMapperImpl.java"
] | [
"data-mapper/src/test/java/com/iluwatar/datamapper/AppTest.java",
"data-mapper/src/test/java/com/iluwatar/datamapper/StudentTest.java"
] | diff --git a/data-mapper/README.md b/data-mapper/README.md
index 7f8b141ee71e..9bf3f1d5124e 100644
--- a/data-mapper/README.md
+++ b/data-mapper/README.md
@@ -1,183 +1,132 @@
---
title: Data Mapper
-category: Architectural
+category: Behavioral
language: en
tag:
-- Decoupling
+ - Data access
+ - Decoupling
+ - Object mapping
+ - Persistence
---
+## Also known as
+
+* Object-Relational Mapping (ORM)
+
## Intent
->Data Mapper is the software layer that separates the in-memory objects from the database.
->Its responsibility is to transfer data between the objects and database and isolate them from each other.
->If we obtain a Data Mapper, it is not necessary for the in-memory object to know if the database exists or not.
->The user could directly manipulate the objects via Java command without having knowledge of SQL or database.
+
+The Data Mapper pattern aims to create an abstraction layer between the database and the business logic, allowing them to evolve independently. It maps data from the database objects to in-memory data structures and vice versa, minimizing direct dependencies between the application's core logic and the underlying database structure.
## Explanation
Real world example
->When a user accesses a specific web page through a browser, he only needs to do several operations to the browser.
-> The browser and the server will take the responsibility of saving data separately.
-> You don't need to know the existence of the server or how to operate the server.
+
+> When a user accesses a specific web page through a browser, he only needs to do several operations to the browser. The browser and the server will take the responsibility of saving data separately. You don't need to know the existence of the server or how to operate the server.
In plain words
->A layer of mappers that moves data between objects and a database while keeping them independent of each other.
+
+> A layer of mappers that moves data between objects and a database while keeping them independent of each other.
Wikipedia says
->A Data Mapper is a Data Access Layer that performs bidirectional transfer of data between a persistent data store
-> (often a relational database) and an in-memory data representation (the domain layer). The goal of the pattern is to
-> keep the in-memory representation and the persistent data store independent of each other and the data mapper itself.
-> This is useful when one needs to model and enforce strict business processes on the data in the domain layer that do
-> not map neatly to the persistent data store.
-**Programmatic Example**
+> A Data Mapper is a Data Access Layer that performs bidirectional transfer of data between a persistent data store (often a relational database) and an in-memory data representation (the domain layer). The goal of the pattern is to keep the in-memory representation and the persistent data store independent of each other and the data mapper itself. This is useful when one needs to model and enforce strict business processes on the data in the domain layer that do not map neatly to the persistent data store.
->We have the student class to defining Students' attributes includes studentId, name and grade.
->We have an interface of StudentDataMapper to lists out the possible behaviour for all possible student mappers.
->And StudentDataMapperImpl class for the implementation of actions on Students Data.
+**Programmatic Example**
-```java
+The Data Mapper is a design pattern that separates the in-memory objects from the database. Its responsibility is to transfer data between the two and also to isolate them from each other. This pattern promotes the [Single Responsibility Principle](https://java-design-patterns.com/principles/#single-responsibility-principle) and [Separation of Concerns](https://java-design-patterns.com/principles/#separation-of-concerns).
-public final class Student implements Serializable {
+In the data-mapper module, the pattern is demonstrated using a Student class and a StudentDataMapper interface.
- private static final long serialVersionUID = 1L;
+The Student class is a simple POJO (Plain Old Java Object) that represents a student. It has properties like studentId, name, and grade.
- @EqualsAndHashCode.Include
+```java
+public class Student {
private int studentId;
private String name;
private char grade;
-
-
- public interface StudentDataMapper {
-
- Optional<Student> find(int studentId);
-
- void insert(Student student) throws DataMapperException;
-
- void update(Student student) throws DataMapperException;
-
- void delete(Student student) throws DataMapperException;
- }
-
- public final class StudentDataMapperImpl implements StudentDataMapper {
- @Override
- public Optional<Student> find(int studentId) {
- return this.getStudents().stream().filter(x -> x.getStudentId() == studentId).findFirst();
- }
-
- @Override
- public void update(Student studentToBeUpdated) throws DataMapperException {
- String name = studentToBeUpdated.getName();
- Integer index = Optional.of(studentToBeUpdated)
- .map(Student::getStudentId)
- .flatMap(this::find)
- .map(students::indexOf)
- .orElseThrow(() -> new DataMapperException("Student [" + name + "] is not found"));
- students.set(index, studentToBeUpdated);
- }
-
- @Override
- public void insert(Student studentToBeInserted) throws DataMapperException {
- Optional<Student> student = find(studentToBeInserted.getStudentId());
- if (student.isPresent()) {
- String name = studentToBeInserted.getName();
- throw new DataMapperException("Student already [" + name + "] exists");
- }
-
- students.add(studentToBeInserted);
- }
-
- @Override
- public void delete(Student studentToBeDeleted) throws DataMapperException {
- if (!students.remove(studentToBeDeleted)) {
- String name = studentToBeDeleted.getName();
- throw new DataMapperException("Student [" + name + "] is not found");
- }
- }
-
- public List<Student> getStudents() {
- return this.students;
- }
- }
+ // ...
}
-
```
->The below example demonstrates basic CRUD operations: Create, Read, Update, and Delete between the in-memory objects
-> and the database.
+The StudentDataMapper interface defines the operations that can be performed on Student objects. These operations include insert, update, delete, and find.
```java
-@Slf4j
-public final class App {
-
- private static final String STUDENT_STRING = "App.main(), student : ";
-
- public static void main(final String... args) {
-
- final var mapper = new StudentDataMapperImpl();
+public interface StudentDataMapper {
+ void insert(final Student student);
- var student = new Student(1, "Adam", 'A');
+ void update(final Student student);
- mapper.insert(student);
+ void delete(final Student student);
- LOGGER.debug(STUDENT_STRING + student + ", is inserted");
+ Optional<Student> find(final int studentId);
+ // ...
+}
+```
- final var studentToBeFound = mapper.find(student.getStudentId());
+The StudentDataMapperImpl class implements the StudentDataMapper interface. It contains the actual logic for interacting with the database.
- LOGGER.debug(STUDENT_STRING + studentToBeFound + ", is searched");
+```java
+public class StudentDataMapperImpl implements StudentDataMapper {
+ // ...
+ @Override
+ public void insert(final Student student) {
+ // Insert student into the database
+ }
- student = new Student(student.getStudentId(), "AdamUpdated", 'A');
+ @Override
+ public void update(final Student student) {
+ // Update student in the database
+ }
- mapper.update(student);
+ @Override
+ public void delete(final Student student) {
+ // Delete student from the database
+ }
- LOGGER.debug(STUDENT_STRING + student + ", is updated");
- LOGGER.debug(STUDENT_STRING + student + ", is going to be deleted");
+ @Override
+ public Optional<Student> find(final int studentId) {
+ // Find student in the database
+ }
+ // ...
+}
+```
- mapper.delete(student);
- }
+The App class contains the main method that demonstrates the use of the StudentDataMapper. It creates a Student object, inserts it into the database, finds it, updates it, and finally deletes it.
- private App() {
- }
+```java
+public class App {
+ public static void main(final String... args) {
+ final var mapper = new StudentDataMapperImpl();
+ var student = new Student(1, "Adam", 'A');
+ mapper.insert(student);
+ final var studentToBeFound = mapper.find(student.getStudentId());
+ student = new Student(student.getStudentId(), "AdamUpdated", 'A');
+ mapper.update(student);
+ mapper.delete(student);
+ }
}
```
Program output:
-15:05:00.264 [main] DEBUG com.iluwatar.datamapper.App - App.main(), student : Student(studentId=1, name=Adam, grade=A), is inserted
-15:05:00.267 [main] DEBUG com.iluwatar.datamapper.App - App.main(), student : Optional[Student(studentId=1, name=Adam, grade=A)], is searched
-15:05:00.268 [main] DEBUG com.iluwatar.datamapper.App - App.main(), student : Student(studentId=1, name=AdamUpdated, grade=A), is updated
-15:05:00.268 [main] DEBUG com.iluwatar.datamapper.App - App.main(), student : Student(studentId=1, name=AdamUpdated, grade=A), is going to be deleted
-
-
-
-This layer consists of one or more mappers (or data access objects) that perform data transfer. The scope of mapper implementations varies.
-A generic mapper will handle many different domain entity types, a dedicated mapper will handle one or a few.
-
-## Explanation
-
-Real-world example
-
-> When accessing web resources through a browser, there is generally no need to interact with the server directly;
-> the browser and the proxy server will complete the data acquisition operation, and the three will remain independent.
-
-In plain words
-
-> The data mapper will help complete the bi-directional transfer of persistence layer and in-memory data.
-
-Wikipedia says
-
-> A Data Mapper is a Data Access Layer that performs bidirectional transfer of data between a
-> persistent data store (often a relational database) and an in-memory data representation (the domain layer).
-
-Programmatic example
+```
+13:54:29.234 [main] DEBUG com.iluwatar.datamapper.App -- App.main(), student : Student(studentId=1, name=Adam, grade=A), is inserted
+13:54:29.237 [main] DEBUG com.iluwatar.datamapper.App -- App.main(), student : Optional[Student(studentId=1, name=Adam, grade=A)], is searched
+13:54:29.237 [main] DEBUG com.iluwatar.datamapper.App -- App.main(), student : Student(studentId=1, name=AdamUpdated, grade=A), is updated
+13:54:29.238 [main] DEBUG com.iluwatar.datamapper.App -- App.main(), student : Student(studentId=1, name=AdamUpdated, grade=A), is going to be deleted
+```
## Class diagram
+
![alt text](./etc/data-mapper.png "Data Mapper")
## Applicability
+
Use the Data Mapper in any of the following situations
-* when you want to decouple data objects from DB access layer
-* when you want to write multiple data retrieval/persistence implementations
+* When there's a need to decouple the in-memory objects from the database entities to promote the [Single Responsibility Principle](https://java-design-patterns.com/principles/#single-responsibility-principle) and [Separation of Concerns](https://java-design-patterns.com/principles/#separation-of-concerns).
+* In applications requiring an ORM tool to bridge the gap between object-oriented models and relational databases.
+* When working with complex database schemas where direct data manipulation and object creation lead to cumbersome and error-prone code.
## Tutorials
@@ -186,16 +135,36 @@ Use the Data Mapper in any of the following situations
* [Data Transfer Object Pattern in Java - Implementation and Mapping (Tutorial for Model Mapper & MapStruct)](https://stackabuse.com/data-transfer-object-pattern-in-java-implementation-and-mapping/)
## Known uses
+
+* ORM frameworks such as Hibernate in Java.
+* Data access layers in enterprise applications where business logic and database management are kept separate.
+* Applications requiring database interactions without tying the code to a specific database implementation.
* [SqlSession.getMapper()](https://mybatis.org/mybatis-3/java-api.html)
## Consequences
-> Neatly mapped persistence layer data
-> Data model follows the single function principle
+Benefits:
+
+* Promotes [Single Responsibility Principle](https://java-design-patterns.com/principles/#single-responsibility-principle) by separating persistence logic from business logic.
+* Enhances maintainability and readability by centralizing data interaction logic.
+* Improves application's ability to adapt to changes in the database schema with minimal changes to the business logic.
+
+Trade-offs:
+
+* Introduces complexity through the additional abstraction layer.
+* Might lead to performance overhead due to the abstraction layer, especially in large-scale applications or with complex queries.
+* Requires developers to learn and understand the abstraction layer in addition to the database and ORM framework being used.
## Related patterns
-* [Active Record Pattern](https://en.wikipedia.org/wiki/Active_record_pattern)
-* [Object–relational Mapping](https://en.wikipedia.org/wiki/Object%E2%80%93relational_mapping)
+
+* Active Record: Combines data access logic and business logic in the domain entities themselves, contrary to Data Mapper's separation of concerns.
+* Object–Relational Mapping (ORM): A technique to map object-oriented programming language data to a relational database.
+* [Repository](https://java-design-patterns.com/patterns/repository/): Provides an abstraction of the data layer, acting as a collection of domain objects in memory.
+* [Unit of Work](https://java-design-patterns.com/patterns/unit-of-work/): Manages transactions and keeps track of the objects affected by a business transaction to ensure changes are consistent and transactional.
## Credits
+
+* Patterns of Enterprise Application Architecture
+* [Java Persistence with Hibernate](https://amzn.to/3VNzlKe)
+* [Clean Architecture: A Craftsman's Guide to Software Structure and Design](https://amzn.to/3xyEFag)
* [Data Mapper](http://richard.jp.leguen.ca/tutoring/soen343-f2010/tutorials/implementing-data-mapper/)
diff --git a/data-mapper/src/main/java/com/iluwatar/datamapper/DataMapperException.java b/data-mapper/src/main/java/com/iluwatar/datamapper/DataMapperException.java
index 3e5419286f70..803adc53114e 100644
--- a/data-mapper/src/main/java/com/iluwatar/datamapper/DataMapperException.java
+++ b/data-mapper/src/main/java/com/iluwatar/datamapper/DataMapperException.java
@@ -24,6 +24,8 @@
*/
package com.iluwatar.datamapper;
+import java.io.Serial;
+
/**
* Using Runtime Exception for avoiding dependency on implementation exceptions. This helps in
* decoupling.
@@ -32,6 +34,7 @@
*/
public final class DataMapperException extends RuntimeException {
+ @Serial
private static final long serialVersionUID = 1L;
/**
diff --git a/data-mapper/src/main/java/com/iluwatar/datamapper/Student.java b/data-mapper/src/main/java/com/iluwatar/datamapper/Student.java
index a2c1007854bf..1691d1233246 100644
--- a/data-mapper/src/main/java/com/iluwatar/datamapper/Student.java
+++ b/data-mapper/src/main/java/com/iluwatar/datamapper/Student.java
@@ -24,6 +24,7 @@
*/
package com.iluwatar.datamapper;
+import java.io.Serial;
import java.io.Serializable;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
@@ -41,6 +42,7 @@
@AllArgsConstructor
public final class Student implements Serializable {
+ @Serial
private static final long serialVersionUID = 1L;
@EqualsAndHashCode.Include
diff --git a/data-mapper/src/main/java/com/iluwatar/datamapper/StudentDataMapperImpl.java b/data-mapper/src/main/java/com/iluwatar/datamapper/StudentDataMapperImpl.java
index 9f7d3c9d967a..9da1c8f7d169 100644
--- a/data-mapper/src/main/java/com/iluwatar/datamapper/StudentDataMapperImpl.java
+++ b/data-mapper/src/main/java/com/iluwatar/datamapper/StudentDataMapperImpl.java
@@ -27,10 +27,12 @@
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
+import lombok.Getter;
/**
* Implementation of Actions on Students Data.
*/
+@Getter
public final class StudentDataMapperImpl implements StudentDataMapper {
/* Note: Normally this would be in the form of an actual database */
@@ -70,8 +72,4 @@ public void delete(Student studentToBeDeleted) throws DataMapperException {
throw new DataMapperException("Student [" + name + "] is not found");
}
}
-
- public List<Student> getStudents() {
- return this.students;
- }
}
| diff --git a/data-mapper/src/test/java/com/iluwatar/datamapper/AppTest.java b/data-mapper/src/test/java/com/iluwatar/datamapper/AppTest.java
index 1f954ff811c8..f45f6cc3266e 100644
--- a/data-mapper/src/test/java/com/iluwatar/datamapper/AppTest.java
+++ b/data-mapper/src/test/java/com/iluwatar/datamapper/AppTest.java
@@ -36,7 +36,6 @@ final class AppTest {
/**
* Issue: Add at least one assertion to this test case.
- *
* Solution: Inserted assertion to check whether the execution of the main method in {@link App#main(String[])}
* throws an exception.
*/
diff --git a/data-mapper/src/test/java/com/iluwatar/datamapper/StudentTest.java b/data-mapper/src/test/java/com/iluwatar/datamapper/StudentTest.java
index e1c3e21edead..9a9866e3bcfc 100644
--- a/data-mapper/src/test/java/com/iluwatar/datamapper/StudentTest.java
+++ b/data-mapper/src/test/java/com/iluwatar/datamapper/StudentTest.java
@@ -41,7 +41,7 @@ final class StudentTest {
* @throws Exception if any execution error during test
*/
@Test
- void testEquality() throws Exception {
+ void testEquality() {
/* Create some students */
final var firstStudent = new Student(1, "Adam", 'A');
| val | test | 2024-04-07T11:15:09 | "2022-10-29T19:58:44Z" | iluwatar | train |
mockito/mockito/134_141 | mockito/mockito | mockito/mockito/134 | mockito/mockito/141 | [
"timestamp(timedelta=4237.0, similarity=0.8425201201576538)"
] | fb455b94118bf03faff3baf665cdb0b8f67d6968 | a2e731bb416949b7e2e4ce096b3454bed310e6eb | [
"Let's fix it in Mockito 2.0\n",
"I'm currently looking at fixing this.\n\nJust to confirm: the current anyX() behaviour is to just accept anything of any type at all (i.e. anyString()/anyInteger()/etc are all the same as anyObject()), and we'd prefer to instead make all of these methods (except anyObject) actually do type checking, and match only nulls and instances of the specified type. Is that right? I'm basing this on https://code.google.com/p/mockito/issues/detail?id=122, which I hope isn't too out of date.\n",
"I think that anyX should not pass for nulls, and should only pass when the object is an instance of given type. Dev team, any thoughts? Might be worth asking on the mailing list what the users think.\n\nWe might also change isA matcher to be consistent and not pass for nulls. This would effectively make anyX an alias to isA.\n",
"The anyX() should either respect the expectation or not exist at all. Working just like anyObject() make it confusing and also pollute the API with a large number of methods.\n",
"I'm with you.\n",
"@szczepiq That's actually the current behaviour of isA, it currently does not match nulls: https://github.com/mockito/mockito/blob/master/src/org/mockito/internal/matchers/InstanceOf.java#L24\n\nI think this means we just want to change all of `anyX()` to be an alias to `isA(X.class)`.\n\nanyObject() still seems like an interesting case there though with this. Having it match nulls makes this API confusingly inconsistent, but I think there is still a strong use case for an ultra-general 'give me anything at all' matcher.\n\nWe could make anyObject() an alias for `any(Object.class)` (so it doesn't accept nulls), and then add `any()` (simpler) or `anything()` (reads nicer in stub setup calls) matchers? I think those could more reasonably accept nulls without feeling inconsistent.\n\nObviously this is all not nicely backward compatible, I'm assuming you're fine with that, since you're heading for 2.0. It's definitely something that will catch people out when they migrate though.\n",
"I think I wouldn't bother changing anyObject(). It's consistent with the family of anyX() methods: anyInt() anyString(), etc. I like the idea of any() alias to anyObject(). Perhaps we could even deprecate anyObject() in favor of any() but I'd rather keep it separate as it is not a backwards incompat change and can be released any time.\n\n> Obviously this is all not nicely backward compatible\n\nIn the changeset, you can include a change to 'version.properties' file that modifes the version to \"2.0.0-beta\". You'll be the first to code Mockito 2.0 feature! :) We would stay on '-beta' version for some time until we make all backwards incompatible changes. Feel free to help more if you want!\n",
"> It's consistent with the family of anyX() methods: anyInt() anyString(), etc.\n\nI don't think it is, is it? With these changes, the below will pass:\n\n``` java\nwhen(mock.stringMethod(anyString())).thenReturn(\"matched\");\nwhen(mock.objectMethod(anyObject())).thenReturn(\"matched\");\n\nassertEquals(\"matched\", mock.stringMethod(\"string\"));\nassertEquals(null, mock.stringMethod(null));\n// vs:\nassertEquals(\"matched\", mock.objectMethod(new Object()));\nassertEquals(\"matched\", mock.objectMethod(null)); // inconsistent\n```\n\n> Feel free to help more if you want!\n\nVery happy to help out more. Any specific issues you want looking at, or issues that are definitely ready for dev, or should I just dive in?\n",
"You can start with this issue :) Let's avoid changing the existing behavior of anyObject() now. We can however think about deprecating it with something like any() (separate discussion).\n",
"PR now in. I've left `anyObject()`, `any()` and `any(X.class)` as is for now (matching everything, including nulls), and just fixed `anyX()` to not match nulls (`anyX()` == `isA(X.class)`)\n",
"Included in 2.0.0-beta. Thanks for help!\n",
"For reference purpose see related work in #510 as well\n"
] | [] | "2014-12-16T01:02:41Z" | [
"bug",
"1.* incompatible"
] | Argument matcher anyXxx() (i.e. anyString(), anyList()) should not match nulls | This is a bug I'm seeing in 1.10.8 version (older version has the same issue - tested with 1.9.0).
Given:
``` java
Function<Object, Integer> function = Mockito.mock(Function.class);
when(function.apply(Mockito.anyString())).thenReturn(1);
Integer result = function.apply(2);
```
Expected behavior:
``` java
result == null;
```
Actual behavior:
``` java
result == 1;
```
Note that the function is called with an integer (not a string), and still the mocked function return the value which it should return only when a string is passed. The same works when using anyBoolean() or any other methof from any\* family.
| [
"src/org/mockito/Matchers.java",
"src/org/mockito/internal/matchers/Any.java",
"version.properties"
] | [
"src/org/mockito/Matchers.java",
"src/org/mockito/internal/matchers/Any.java",
"version.properties"
] | [
"test/org/mockitousage/IMethods.java",
"test/org/mockitousage/MethodsImpl.java",
"test/org/mockitousage/matchers/AnyXMatchersAcceptNullsTest.java",
"test/org/mockitousage/matchers/MatchersTest.java",
"test/org/mockitousage/matchers/NewMatchersTest.java",
"test/org/mockitousage/verification/DescriptiveMessagesWhenVerificationFailsTest.java",
"test/org/mockitousage/verification/PrintingVerboseTypesWithArgumentsTest.java"
] | diff --git a/src/org/mockito/Matchers.java b/src/org/mockito/Matchers.java
index 789d598bb4..a8b71dc79e 100644
--- a/src/org/mockito/Matchers.java
+++ b/src/org/mockito/Matchers.java
@@ -50,13 +50,6 @@
* This implementation is due static type safety imposed by java compiler.
* The consequence is that you cannot use <code>anyObject()</code>, <code>eq()</code> methods outside of verified/stubbed method.
*
- * <p>
- * <b>Warning 2:</b>
- * <p>
- * The any family methods <b>*don't do any type checks*</b>, those are only here to avoid casting
- * in your code. If you want to perform type checks use the {@link #isA(Class)} method.
- * This <b>might</b> however change (type checks could be added) in a future major release.
- *
* <h1>Custom Argument Matchers</h1>
*
* Use {@link Matchers#argThat} method and pass an instance of hamcrest {@link Matcher}.
@@ -107,133 +100,97 @@ public class Matchers {
private static final MockingProgress MOCKING_PROGRESS = new ThreadSafeMockingProgress();
/**
- * Any <code>boolean</code>, <code>Boolean</code> or <code>null</code>.
- * <p>
- * This method <b>*don't do any type checks*</b>, it is only there to avoid casting
- * in your code. This might however change (type checks could be added) in a
- * future major release.
+ * Any <code>boolean</code> or non-null <code>Boolean</code>
* <p>
* See examples in javadoc for {@link Matchers} class
*
* @return <code>false</code>.
*/
public static boolean anyBoolean() {
- return reportMatcher(Any.ANY).returnFalse();
+ return reportMatcher(new InstanceOf(Boolean.class)).returnFalse();
}
/**
- * Any <code>byte</code>, <code>Byte</code> or <code>null</code>.
- * <p>
- * This method <b>*don't do any type checks*</b>, it is only there to avoid casting
- * in your code. This might however change (type checks could be added) in a
- * future major release.
+ * Any <code>byte</code> or non-null <code>Byte</code>.
* <p>
* See examples in javadoc for {@link Matchers} class
*
* @return <code>0</code>.
*/
public static byte anyByte() {
- return reportMatcher(Any.ANY).returnZero();
+ return reportMatcher(new InstanceOf(Byte.class)).returnZero();
}
/**
- * Any <code>char</code>, <code>Character</code> or <code>null</code>.
- * <p>
- * This method <b>*don't do any type checks*</b>, it is only there to avoid casting
- * in your code. This might however change (type checks could be added) in a
- * future major release.
+ * Any <code>char</code> or non-null <code>Character</code>.
* <p>
* See examples in javadoc for {@link Matchers} class
*
* @return <code>0</code>.
*/
public static char anyChar() {
- return reportMatcher(Any.ANY).returnChar();
+ return reportMatcher(new InstanceOf(Character.class)).returnChar();
}
/**
- * Any int, Integer or <code>null</code>.
- * <p>
- * This method <b>*don't do any type checks*</b>, it is only there to avoid casting
- * in your code. This might however change (type checks could be added) in a
- * future major release.
+ * Any int or non-null Integer.
* <p>
* See examples in javadoc for {@link Matchers} class
*
* @return <code>0</code>.
*/
public static int anyInt() {
- return reportMatcher(Any.ANY).returnZero();
+ return reportMatcher(new InstanceOf(Integer.class)).returnZero();
}
/**
- * Any <code>long</code>, <code>Long</code> or <code>null</code>.
- * <p>
- * This method <b>*don't do any type checks*</b>, it is only there to avoid casting
- * in your code. This might however change (type checks could be added) in a
- * future major release.
+ * Any <code>long</code> or non-null <code>Long</code>.
* <p>
* See examples in javadoc for {@link Matchers} class
*
* @return <code>0</code>.
*/
public static long anyLong() {
- return reportMatcher(Any.ANY).returnZero();
+ return reportMatcher(new InstanceOf(Long.class)).returnZero();
}
/**
- * Any <code>float</code>, <code>Float</code> or <code>null</code>.
- * <p>
- * This method <b>*don't do any type checks*</b>, it is only there to avoid casting
- * in your code. This might however change (type checks could be added) in a
- * future major release.
+ * Any <code>float</code> or non-null <code>Float</code>.
* <p>
* See examples in javadoc for {@link Matchers} class
*
* @return <code>0</code>.
*/
public static float anyFloat() {
- return reportMatcher(Any.ANY).returnZero();
+ return reportMatcher(new InstanceOf(Float.class)).returnZero();
}
/**
- * Any <code>double</code>, <code>Double</code> or <code>null</code>.
- * <p>
- * This method <b>*don't do any type checks*</b>, it is only there to avoid casting
- * in your code. This might however change (type checks could be added) in a
- * future major release.
+ * Any <code>double</code> or non-null <code>Double</code>.
* <p>
* See examples in javadoc for {@link Matchers} class
*
* @return <code>0</code>.
*/
public static double anyDouble() {
- return reportMatcher(Any.ANY).returnZero();
+ return reportMatcher(new InstanceOf(Double.class)).returnZero();
}
/**
- * Any <code>short</code>, <code>Short</code> or <code>null</code>.
- * <p>
- * This method <b>*don't do any type checks*</b>, it is only there to avoid casting
- * in your code. This might however change (type checks could be added) in a
- * future major release.
+ * Any <code>short</code> or non-null <code>Short</code>.
* <p>
* See examples in javadoc for {@link Matchers} class
*
* @return <code>0</code>.
*/
public static short anyShort() {
- return reportMatcher(Any.ANY).returnZero();
+ return reportMatcher(new InstanceOf(Short.class)).returnZero();
}
/**
- * Any <code>Object</code> or <code>null</code>.
- * <p>
- * This method <b>*don't do any type checks*</b>, it is only there to avoid casting
- * in your code. This might however change (type checks could be added) in a
- * future major release.
+ * Matches anything, including null.
* <p>
- * Has aliases: {@link #any()} and {@link #any(Class clazz)}
+ * This is an alias of: {@link #any()} and {@link #any(java.lang.Class)}
* <p>
* See examples in javadoc for {@link Matchers} class
*
@@ -271,20 +228,16 @@ public static <T> T anyVararg() {
}
/**
- * Any kind object, not necessary of the given class.
- * The class argument is provided only to avoid casting.
+ * Matches any object, including nulls
* <p>
- * Sometimes looks better than <code>anyObject()</code> - especially when explicit casting is required
+ * This method doesn't do type checks with the given parameter, it is only there
+ * to avoid casting in your code. This might however change (type checks could
+ * be added) in a future major release.
* <p>
- * Alias to {@link Matchers#anyObject()}
+ * See examples in javadoc for {@link Matchers} class
* <p>
- * This method <b>*don't do any type checks*</b>, it is only there to avoid casting
- * in your code. This might however change (type checks could be added) in a
- * future major release.
+ * This is an alias of: {@link #any()} and {@link #anyObject()}
* <p>
- * See examples in javadoc for {@link Matchers} class
- *
- * @param clazz The type to avoid casting
* @return <code>null</code>.
*/
public static <T> T any(Class<T> clazz) {
@@ -292,61 +245,51 @@ public static <T> T any(Class<T> clazz) {
}
/**
- * Any object or <code>null</code>.
+ * Matches anything, including nulls
* <p>
* Shorter alias to {@link Matchers#anyObject()}
* <p>
- * This method <b>*don't do any type checks*</b>, it is only there to avoid casting
- * in your code. This might however change (type checks could be added) in a
- * future major release.
- * <p>
* See examples in javadoc for {@link Matchers} class
- *
+ * <p>
+ * This is an alias of: {@link #anyObject()} and {@link #any(java.lang.Class)}
+ * <p>
* @return <code>null</code>.
*/
public static <T> T any() {
- return (T) anyObject();
+ return anyObject();
}
/**
- * Any <code>String</code> or <code>null</code>.
- * <p>
- * This method <b>*don't do any type checks*</b>, it is only there to avoid casting
- * in your code. This might however change (type checks could be added) in a
- * future major release.
+ * Any non-null <code>String</code>
* <p>
* See examples in javadoc for {@link Matchers} class
*
* @return empty String ("")
*/
public static String anyString() {
- return reportMatcher(Any.ANY).returnString();
+ return reportMatcher(new InstanceOf(String.class)).returnString();
}
/**
- * Any <code>List</code> or <code>null</code>.
- * <p>
- * This method <b>*don't do any type checks*</b>, it is only there to avoid casting
- * in your code. This might however change (type checks could be added) in a
- * future major release.
+ * Any non-null <code>List</code>.
* <p>
* See examples in javadoc for {@link Matchers} class
*
* @return empty List.
*/
public static List anyList() {
- return reportMatcher(Any.ANY).returnList();
- }
+ return reportMatcher(new InstanceOf(List.class)).returnList();
+ }
/**
* Generic friendly alias to {@link Matchers#anyList()}.
* It's an alternative to @SuppressWarnings("unchecked") to keep code clean of compiler warnings.
* <p>
- * Any <code>List</code> or <code>null</code>.
+ * Any non-null <code>List</code>.
* <p>
- * This method <b>*don't do any type checks*</b>, it is only there to avoid casting
- * in your code. This might however change (type checks could be added) in a
- * future major release.
+ * This method doesn't do type checks with the given parameter, it is only there
+ * to avoid casting in your code. This might however change (type checks could
+ * be added) in a future major release.
* <p>
* See examples in javadoc for {@link Matchers} class
*
@@ -354,33 +297,29 @@ public static List anyList() {
* @return empty List.
*/
public static <T> List<T> anyListOf(Class<T> clazz) {
- return (List) reportMatcher(Any.ANY).returnList();
- }
+ return anyList();
+ }
/**
- * Any <code>Set</code> or <code>null</code>.
- * <p>
- * This method <b>*don't do any type checks*</b>, it is only there to avoid casting
- * in your code. This might however change (type checks could be added) in a
- * future major release.
+ * Any non-null <code>Set</code>.
* <p>
* See examples in javadoc for {@link Matchers} class
*
* @return empty Set
*/
public static Set anySet() {
- return reportMatcher(Any.ANY).returnSet();
+ return reportMatcher(new InstanceOf(Set.class)).returnSet();
}
/**
* Generic friendly alias to {@link Matchers#anySet()}.
* It's an alternative to @SuppressWarnings("unchecked") to keep code clean of compiler warnings.
* <p>
- * Any <code>Set</code> or <code>null</code>
+ * Any non-null <code>Set</code>.
* <p>
- * This method <b>*don't do any type checks*</b>, it is only there to avoid casting
- * in your code. This might however change (type checks could be added) in a
- * future major release.
+ * This method doesn't do type checks with the given parameter, it is only there
+ * to avoid casting in your code. This might however change (type checks could
+ * be added) in a future major release.
* <p>
* See examples in javadoc for {@link Matchers} class
*
@@ -388,33 +327,29 @@ public static Set anySet() {
* @return empty Set
*/
public static <T> Set<T> anySetOf(Class<T> clazz) {
- return (Set) reportMatcher(Any.ANY).returnSet();
+ return anySet();
}
/**
- * Any <code>Map</code> or <code>null</code>.
- * <p>
- * This method <b>*don't do any type checks*</b>, it is only there to avoid casting
- * in your code. This might however change (type checks could be added) in a
- * future major release.
+ * Any non-null <code>Map</code>.
* <p>
* See examples in javadoc for {@link Matchers} class
*
* @return empty Map.
*/
public static Map anyMap() {
- return reportMatcher(Any.ANY).returnMap();
+ return reportMatcher(new InstanceOf(Map.class)).returnMap();
}
/**
* Generic friendly alias to {@link Matchers#anyMap()}.
* It's an alternative to @SuppressWarnings("unchecked") to keep code clean of compiler warnings.
* <p>
- * Any <code>Map</code> or <code>null</code>
+ * Any non-null <code>Map</code>.
* <p>
- * This method <b>*don't do any type checks*</b>, it is only there to avoid casting
- * in your code. This might however change (type checks could be added) in a
- * future major release.
+ * This method doesn't do type checks with the given parameter, it is only there
+ * to avoid casting in your code. This might however change (type checks could
+ * be added) in a future major release.
* <p>
* See examples in javadoc for {@link Matchers} class
*
@@ -423,33 +358,29 @@ public static Map anyMap() {
* @return empty Map.
*/
public static <K, V> Map<K, V> anyMapOf(Class<K> keyClazz, Class<V> valueClazz) {
- return reportMatcher(Any.ANY).returnMap();
+ return anyMap();
}
/**
- * Any <code>Collection</code> or <code>null</code>.
- * <p>
- * This method <b>*don't do any type checks*</b>, it is only there to avoid casting
- * in your code. This might however change (type checks could be added) in a
- * future major release.
+ * Any non-null <code>Collection</code>.
* <p>
* See examples in javadoc for {@link Matchers} class
*
* @return empty Collection.
*/
public static Collection anyCollection() {
- return reportMatcher(Any.ANY).returnList();
+ return reportMatcher(new InstanceOf(Collection.class)).returnList();
}
/**
* Generic friendly alias to {@link Matchers#anyCollection()}.
- * It's an alternative to @SuppressWarnings("unchecked") to keep code clean of compiler warnings.
+ * It's an alternative to @SuppressWarnings("unchecked") to keep code clean of compiler warnings.
* <p>
- * Any <code>Collection</code> or <code>null</code>.
+ * Any non-null <code>Collection</code>.
* <p>
- * This method <b>*don't do any type checks*</b>, it is only there to avoid casting
- * in your code. This might however change (type checks could be added) in a
- * future major release.
+ * This method doesn't do type checks with the given parameter, it is only there
+ * to avoid casting in your code. This might however change (type checks could
+ * be added) in a future major release.
* <p>
* See examples in javadoc for {@link Matchers} class
*
@@ -457,7 +388,7 @@ public static Collection anyCollection() {
* @return empty Collection.
*/
public static <T> Collection<T> anyCollectionOf(Class<T> clazz) {
- return (Collection) reportMatcher(Any.ANY).returnList();
+ return anyCollection();
}
/**
diff --git a/src/org/mockito/internal/matchers/Any.java b/src/org/mockito/internal/matchers/Any.java
index 1876b38cf2..28a98f027a 100644
--- a/src/org/mockito/internal/matchers/Any.java
+++ b/src/org/mockito/internal/matchers/Any.java
@@ -14,7 +14,7 @@
public class Any extends ArgumentMatcher implements Serializable {
private static final long serialVersionUID = -4062420125651019029L;
- public static final Any ANY = new Any();
+ public static final Any ANY = new Any();
private Any() {}
diff --git a/version.properties b/version.properties
index 0e4d43bdff..c3d41c20f9 100644
--- a/version.properties
+++ b/version.properties
@@ -1,2 +1,2 @@
-version=1.10.17
+version=2.0.0-beta
mockito.testng.version=1.0
\ No newline at end of file
| diff --git a/test/org/mockitousage/IMethods.java b/test/org/mockitousage/IMethods.java
index 557e7c5e14..8c9a1b3359 100644
--- a/test/org/mockitousage/IMethods.java
+++ b/test/org/mockitousage/IMethods.java
@@ -219,4 +219,6 @@ public interface IMethods {
int toIntPrimitive(Integer i);
Integer toIntWrapper(int i);
+
+ String forObject(Object object);
}
\ No newline at end of file
diff --git a/test/org/mockitousage/MethodsImpl.java b/test/org/mockitousage/MethodsImpl.java
index 539f612de7..347dfa65f6 100644
--- a/test/org/mockitousage/MethodsImpl.java
+++ b/test/org/mockitousage/MethodsImpl.java
@@ -418,4 +418,8 @@ public int toIntPrimitive(Integer i) {
public Integer toIntWrapper(int i) {
return null;
}
+
+ public String forObject(Object object) {
+ return null;
+ }
}
diff --git a/test/org/mockitousage/matchers/AnyXMatchersAcceptNullsTest.java b/test/org/mockitousage/matchers/AnyXMatchersAcceptNullsTest.java
index 32c7b6f605..b5d767fe64 100644
--- a/test/org/mockitousage/matchers/AnyXMatchersAcceptNullsTest.java
+++ b/test/org/mockitousage/matchers/AnyXMatchersAcceptNullsTest.java
@@ -24,24 +24,37 @@ public void setUp() {
}
@Test
- public void shouldAnyXMatchersAcceptNull() {
- when(mock.oneArg(anyObject())).thenReturn("0");
- when(mock.oneArg(anyString())).thenReturn("1");
- when(mock.forList(anyList())).thenReturn("2");
- when(mock.forMap(anyMap())).thenReturn("3");
- when(mock.forCollection(anyCollection())).thenReturn("4");
- when(mock.forSet(anySet())).thenReturn("5");
+ public void shouldAcceptNullsInAnyMatcher() {
+ when(mock.oneArg(any())).thenReturn("matched");
+
+ assertEquals(null, mock.forObject(null));
+ }
+
+ @Test
+ public void shouldAcceptNullsInAnyObjectMatcher() {
+ when(mock.oneArg(anyObject())).thenReturn("matched");
+
+ assertEquals(null, mock.forObject(null));
+ }
+
+ @Test
+ public void shouldNotAcceptNullInAnyXMatchers() {
+ when(mock.oneArg(anyString())).thenReturn("0");
+ when(mock.forList(anyList())).thenReturn("1");
+ when(mock.forMap(anyMap())).thenReturn("2");
+ when(mock.forCollection(anyCollection())).thenReturn("3");
+ when(mock.forSet(anySet())).thenReturn("4");
- assertEquals("0", mock.oneArg((Object) null));
- assertEquals("1", mock.oneArg((String) null));
- assertEquals("2", mock.forList(null));
- assertEquals("3", mock.forMap(null));
- assertEquals("4", mock.forCollection(null));
- assertEquals("5", mock.forSet(null));
+ assertEquals(null, mock.oneArg((Object) null));
+ assertEquals(null, mock.oneArg((String) null));
+ assertEquals(null, mock.forList(null));
+ assertEquals(null, mock.forMap(null));
+ assertEquals(null, mock.forCollection(null));
+ assertEquals(null, mock.forSet(null));
}
@Test
- public void shouldAnyPrimiteWraperMatchersAcceptNull() {
+ public void shouldNotAcceptNullInAllAnyPrimitiveWrapperMatchers() {
when(mock.forInteger(anyInt())).thenReturn("0");
when(mock.forCharacter(anyChar())).thenReturn("1");
when(mock.forShort(anyShort())).thenReturn("2");
@@ -51,13 +64,13 @@ public void shouldAnyPrimiteWraperMatchersAcceptNull() {
when(mock.forFloat(anyFloat())).thenReturn("6");
when(mock.forDouble(anyDouble())).thenReturn("7");
- assertEquals("0", mock.forInteger(null));
- assertEquals("1", mock.forCharacter(null));
- assertEquals("2", mock.forShort(null));
- assertEquals("3", mock.forByte(null));
- assertEquals("4", mock.forBoolean(null));
- assertEquals("5", mock.forLong(null));
- assertEquals("6", mock.forFloat(null));
- assertEquals("7", mock.forDouble(null));
+ assertEquals(null, mock.forInteger(null));
+ assertEquals(null, mock.forCharacter(null));
+ assertEquals(null, mock.forShort(null));
+ assertEquals(null, mock.forByte(null));
+ assertEquals(null, mock.forBoolean(null));
+ assertEquals(null, mock.forLong(null));
+ assertEquals(null, mock.forFloat(null));
+ assertEquals(null, mock.forDouble(null));
}
}
\ No newline at end of file
diff --git a/test/org/mockitousage/matchers/MatchersTest.java b/test/org/mockitousage/matchers/MatchersTest.java
index 9835bbd660..971a84c84b 100644
--- a/test/org/mockitousage/matchers/MatchersTest.java
+++ b/test/org/mockitousage/matchers/MatchersTest.java
@@ -225,15 +225,25 @@ public void compareToMatcher() {
@Test
public void anyStringMatcher() {
- when(mock.oneArg(anyString())).thenReturn("1");
+ when(mock.oneArg(anyString())).thenReturn("matched");
- assertEquals("1", mock.oneArg(""));
- assertEquals("1", mock.oneArg("any string"));
- assertEquals(null, mock.oneArg((Object) null));
+ assertEquals("matched", mock.oneArg(""));
+ assertEquals("matched", mock.oneArg("any string"));
+ assertEquals(null, mock.oneArg((String) null));
}
@Test
public void anyMatcher() {
+ when(mock.forObject(any())).thenReturn("matched");
+
+ assertEquals("matched", mock.forObject(123));
+ assertEquals("matched", mock.forObject("any string"));
+ assertEquals("matched", mock.forObject("any string"));
+ assertEquals("matched", mock.forObject((Object) null));
+ }
+
+ @Test
+ public void anyXMatcher() {
when(mock.oneArg(anyBoolean())).thenReturn("0");
when(mock.oneArg(anyByte())).thenReturn("1");
when(mock.oneArg(anyChar())).thenReturn("2");
diff --git a/test/org/mockitousage/matchers/NewMatchersTest.java b/test/org/mockitousage/matchers/NewMatchersTest.java
index 77874f3a60..e9e8f16e13 100644
--- a/test/org/mockitousage/matchers/NewMatchersTest.java
+++ b/test/org/mockitousage/matchers/NewMatchersTest.java
@@ -29,41 +29,41 @@ public void setUp() {
@Test
public void shouldAllowAnyList() {
- when(mock.forList(anyList())).thenReturn("x");
+ when(mock.forList(anyList())).thenReturn("matched");
- assertEquals("x", mock.forList(null));
- assertEquals("x", mock.forList(Arrays.asList("x", "y")));
-
- verify(mock, times(2)).forList(anyList());
+ assertEquals("matched", mock.forList(Arrays.asList("x", "y")));
+ assertEquals(null, mock.forList(null));
+
+ verify(mock, times(1)).forList(anyList());
}
@Test
public void shouldAllowAnyCollection() {
- when(mock.forCollection(anyCollection())).thenReturn("x");
+ when(mock.forCollection(anyCollection())).thenReturn("matched");
- assertEquals("x", mock.forCollection(null));
- assertEquals("x", mock.forCollection(Arrays.asList("x", "y")));
-
- verify(mock, times(2)).forCollection(anyCollection());
+ assertEquals("matched", mock.forCollection(Arrays.asList("x", "y")));
+ assertEquals(null, mock.forCollection(null));
+
+ verify(mock, times(1)).forCollection(anyCollection());
}
@Test
public void shouldAllowAnyMap() {
- when(mock.forMap(anyMap())).thenReturn("x");
+ when(mock.forMap(anyMap())).thenReturn("matched");
- assertEquals("x", mock.forMap(null));
- assertEquals("x", mock.forMap(new HashMap<String, String>()));
-
- verify(mock, times(2)).forMap(anyMap());
+ assertEquals("matched", mock.forMap(new HashMap<String, String>()));
+ assertEquals(null, mock.forMap(null));
+
+ verify(mock, times(1)).forMap(anyMap());
}
@Test
public void shouldAllowAnySet() {
- when(mock.forSet(anySet())).thenReturn("x");
+ when(mock.forSet(anySet())).thenReturn("matched");
- assertEquals("x", mock.forSet(null));
- assertEquals("x", mock.forSet(new HashSet<String>()));
-
- verify(mock, times(2)).forSet(anySet());
+ assertEquals("matched", mock.forSet(new HashSet<String>()));
+ assertEquals(null, mock.forSet(null));
+
+ verify(mock, times(1)).forSet(anySet());
}
}
\ No newline at end of file
diff --git a/test/org/mockitousage/verification/DescriptiveMessagesWhenVerificationFailsTest.java b/test/org/mockitousage/verification/DescriptiveMessagesWhenVerificationFailsTest.java
index 65f6bdbe31..44a074ef5c 100644
--- a/test/org/mockitousage/verification/DescriptiveMessagesWhenVerificationFailsTest.java
+++ b/test/org/mockitousage/verification/DescriptiveMessagesWhenVerificationFailsTest.java
@@ -239,7 +239,10 @@ public void should_print_method_when_matcher_used() throws Exception {
"\n" +
"Wanted but not invoked:" +
"\n" +
- "iMethods.twoArgumentMethod(<any>, 100);";
+ "iMethods.twoArgumentMethod(\n" +
+ " isA(java.lang.Integer),\n" +
+ " 100\n" +
+ ");";
assertContains(expectedMessage, actualMessage);
}
}
diff --git a/test/org/mockitousage/verification/PrintingVerboseTypesWithArgumentsTest.java b/test/org/mockitousage/verification/PrintingVerboseTypesWithArgumentsTest.java
index e222c95022..05543dd339 100644
--- a/test/org/mockitousage/verification/PrintingVerboseTypesWithArgumentsTest.java
+++ b/test/org/mockitousage/verification/PrintingVerboseTypesWithArgumentsTest.java
@@ -65,12 +65,12 @@ public void shouldShowTheTypeOfTheMismatchingArgumentWhenOutputDescriptionsForIn
try {
//when
- verify(boo).withLongAndInt(eq(100), anyInt());
+ verify(boo).withLongAndInt(eq(100), any(Integer.class));
fail();
} catch (ArgumentsAreDifferent e) {
//then
assertContains("withLongAndInt((Long) 100, 200)", e.getMessage());
- assertContains("withLongAndInt((Integer) 100, <any>)", e.getMessage());
+ assertContains("withLongAndInt((Integer) 100, <any>", e.getMessage());
}
}
| train | train | 2014-12-16T00:25:31 | "2014-12-12T10:20:31Z" | alexo | train |
mockito/mockito/157_158 | mockito/mockito | mockito/mockito/157 | mockito/mockito/158 | [
"timestamp(timedelta=75.0, similarity=0.9395389559265163)"
] | fff76563d9e0ed412dc828c53cfdc7d142997a31 | d645862386143a8ae7d6bd122d0fcfa71c02e339 | [
"Duplicate of #28\nThough the team thought it was better for project that don't rely on maven like source repositories.\ncc @szczepiq \n"
] | [] | "2015-01-15T12:36:35Z" | [] | Source files should not be put in binary JAR | Source files (`*.java`) should not be put into binary `mockito-core.jar`. It stupefies Idea to show decompiled file even when source jar is available.
| [
"build.gradle"
] | [
"build.gradle"
] | [] | diff --git a/build.gradle b/build.gradle
index 94ebdaf3cc..3ed8f310c0 100644
--- a/build.gradle
+++ b/build.gradle
@@ -71,7 +71,7 @@ def licenseFiles = copySpec {
jar {
baseName = 'mockito-core'
- from(sourceSets.main.allSource)
+ from(sourceSets.main.output)
from(zipTree("lib/repackaged/cglib-and-asm-1.0.jar")) {
exclude 'META-INF/MANIFEST.MF'
}
| null | train | train | 2015-01-04T13:44:24 | "2015-01-15T12:36:02Z" | szpak | train |
mockito/mockito/172_175 | mockito/mockito | mockito/mockito/172 | mockito/mockito/175 | [
"timestamp(timedelta=2984.0, similarity=0.9343794448096776)"
] | 44fbd4985cb7448b727df60df398c1b7705b7602 | 9943c7c00d1480f3d778c6ca8b990c039d5c533c | [
"I agree.\nIt would be nice to depend on a version of hamcrest-core that is not eight years old...\n",
"Hi thanks for your interest. I think your comment are indeed just right, yet compatibility has always been the primary concern here.\n\nNevertheless mockito 2.0.x will probably ditch the hamcrest dependency. We still have to think that through. But it will happen, hence the reason why we didn't merge this PR.\n",
"Cool, thank you for the update! Cheers!\n"
] | [] | "2015-02-22T19:22:34Z" | [] | Update hamcrest-core to version 1.3 | Hi there,
It would be nice if mockito-core would depend on hamcrest-core 1.3 instead of 1.1 so that both mockito and junit [latest versions] would depend on the same 3rd party library.
Thanks in advance!
| [
"build.gradle",
"src/org/mockito/internal/matchers/LocalizedMatcher.java"
] | [
"build.gradle",
"src/org/mockito/internal/matchers/LocalizedMatcher.java"
] | [
"test/org/mockito/internal/runners/RunnerFactoryTest.java",
"test/org/mockitousage/basicapi/MocksCreationTest.java",
"test/org/mockitoutil/ExtraMatchers.java"
] | diff --git a/build.gradle b/build.gradle
index 66145a4d0e..0ec718a1a5 100644
--- a/build.gradle
+++ b/build.gradle
@@ -61,7 +61,7 @@ tasks.withType(JavaCompile) {
//TODO we should remove all dependencies to checked-in jars
dependencies {
provided "junit:junit:4.10"
- compile "org.hamcrest:hamcrest-core:1.1", "org.objenesis:objenesis:2.1"
+ compile "org.hamcrest:hamcrest-core:1.3", "org.objenesis:objenesis:2.1"
compile fileTree('lib/repackaged') { exclude '*.txt'}
testCompile fileTree("lib/test")
diff --git a/src/org/mockito/internal/matchers/LocalizedMatcher.java b/src/org/mockito/internal/matchers/LocalizedMatcher.java
index b19cdf5133..d770103286 100644
--- a/src/org/mockito/internal/matchers/LocalizedMatcher.java
+++ b/src/org/mockito/internal/matchers/LocalizedMatcher.java
@@ -64,6 +64,10 @@ public void captureFrom(Object argument) {
}
}
+ public void describeMismatch(Object argument, Description description) {
+ actualMatcher.describeMismatch(argument, description);
+ }
+
//TODO: refactor other 'delegated interfaces' to use the MatcherDecorator feature
public Matcher getActualMatcher() {
return actualMatcher;
| diff --git a/test/org/mockito/internal/runners/RunnerFactoryTest.java b/test/org/mockito/internal/runners/RunnerFactoryTest.java
index 02c7abdd3b..e012bbdeef 100644
--- a/test/org/mockito/internal/runners/RunnerFactoryTest.java
+++ b/test/org/mockito/internal/runners/RunnerFactoryTest.java
@@ -1,7 +1,7 @@
-/*
- * Copyright (c) 2007 Mockito contributors
- * This program is made available under the terms of the MIT License.
- */
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
package org.mockito.internal.runners;
import static org.hamcrest.CoreMatchers.*;
@@ -37,7 +37,7 @@ public boolean isJUnit45OrHigherAvailable() {
RunnerImpl runner = factory.create(RunnerFactoryTest.class);
//then
- assertThat(runner, is(JUnit44RunnerImpl.class));
+ assertThat(runner, instanceOf(JUnit44RunnerImpl.class));
}
@Test
@@ -54,7 +54,7 @@ public boolean isJUnit45OrHigherAvailable() {
RunnerImpl runner = factory.create(RunnerFactoryTest.class);
//then
- assertThat(runner, is(JUnit45AndHigherRunnerImpl.class));
+ assertThat(runner, instanceOf(JUnit45AndHigherRunnerImpl.class));
}
@Test
diff --git a/test/org/mockitousage/basicapi/MocksCreationTest.java b/test/org/mockitousage/basicapi/MocksCreationTest.java
index 533826a6f4..e2e532de86 100644
--- a/test/org/mockitousage/basicapi/MocksCreationTest.java
+++ b/test/org/mockitousage/basicapi/MocksCreationTest.java
@@ -16,7 +16,7 @@
import java.util.List;
import java.util.Set;
-import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.instanceOf;
import static org.mockito.Mockito.*;
@SuppressWarnings("unchecked")
@@ -62,7 +62,7 @@ public void shouldCombineMockNameAndExtraInterfaces() {
//then
assertContains("great mockie", name);
//and
- assertThat(mock, is(List.class));
+ assertThat(mock, instanceOf(List.class));
}
@Test
diff --git a/test/org/mockitoutil/ExtraMatchers.java b/test/org/mockitoutil/ExtraMatchers.java
index bd0fe349ec..eb3e94bb9a 100644
--- a/test/org/mockitoutil/ExtraMatchers.java
+++ b/test/org/mockitoutil/ExtraMatchers.java
@@ -133,7 +133,7 @@ public void assertValue(Collection value) {
};
}
- public static org.hamcrest.Matcher<java.lang.Object> clazz(java.lang.Class<?> type) {
+ public static <T> org.hamcrest.Matcher<T> clazz(java.lang.Class<T> type) {
return CoreMatchers.is(type);
}
| val | train | 2015-02-16T02:17:52 | "2015-02-17T11:52:22Z" | ghost | train |
mockito/mockito/200_201 | mockito/mockito | mockito/mockito/200 | mockito/mockito/201 | [
"timestamp(timedelta=1.0, similarity=0.8791892604278365)",
"keyword_pr_to_issue"
] | d3fd493288ccbdf1bf54d7d1ea0bb6c96ddc6d57 | 4a34cbe64cf93f2a275559e3613c5b2f074b235d | [
"PR #201\n"
] | [] | "2015-04-16T16:46:50Z" | [
"enhancement"
] | ArgumentCaptor.fromClass's return type should match a parameterized type | `ArgumentCaptor.fromClass`'s return type should match a parameterized type. I.e. the expression `ArgumentCaptor.fromClass(Class<S>)` should be of type `ArgumentCaptor<U>` where `S` is a subtype of `U`.
For example:
```
ArgumentCaptor<Consumer<String>> captor = ArgumentCaptor.fromClass(Consumer.class)
```
does not type check (i.e. it is a compile time error). It should type check.
The reasons that it is desirable for `ArgumentCaptor.fromClass` to allow expressions such as the example above to type check are:
1) `ArgumentCaptor.fromClass` is intended to be a convenience method to allow the user to construct an ArgumentCaptor without casting the returned value.
Currently, the user can devise a workaround such as:
```
ArgumentCaptor<? extends Consumer<String>> captor
= ArgumentCaptor.fromClass(Consumer.class)
```
This workaround is inconvenient, and so contrary to `ArgumentCaptor.fromClass` being a convenience method.
2) It is inconsistent with `@Captor`, which can be applied to a field with a paramterized type. I.e.
```
@Captor ArgumentCaptor<Consumer<String>> captor
```
type checks.
| [
"src/org/mockito/ArgumentCaptor.java"
] | [
"src/org/mockito/ArgumentCaptor.java"
] | [
"test/org/mockitousage/matchers/CapturingArgumentsTest.java"
] | diff --git a/src/org/mockito/ArgumentCaptor.java b/src/org/mockito/ArgumentCaptor.java
index 0efe061cf7..78c41c89f9 100644
--- a/src/org/mockito/ArgumentCaptor.java
+++ b/src/org/mockito/ArgumentCaptor.java
@@ -65,7 +65,7 @@ public class ArgumentCaptor<T> {
HandyReturnValues handyReturnValues = new HandyReturnValues();
private final CapturingMatcher<T> capturingMatcher = new CapturingMatcher<T>();
- private final Class<T> clazz;
+ private final Class<? extends T> clazz;
/**
* @deprecated
@@ -87,7 +87,7 @@ public ArgumentCaptor() {
this.clazz = null;
}
- ArgumentCaptor(Class<T> clazz) {
+ private ArgumentCaptor(Class<? extends T> clazz) {
this.clazz = clazz;
}
@@ -163,10 +163,11 @@ public List<T> getAllValues() {
* future major release.
*
* @param clazz Type matching the parameter to be captured.
- * @param <T> Type of clazz
+ * @param <S> Type of clazz
+ * @param <U> Type of object captured by the newly built ArgumentCaptor
* @return A new ArgumentCaptor
*/
- public static <T> ArgumentCaptor<T> forClass(Class<T> clazz) {
- return new ArgumentCaptor<T>(clazz);
+ public static <U,S extends U> ArgumentCaptor<U> forClass(Class<S> clazz) {
+ return new ArgumentCaptor<U>(clazz);
}
}
\ No newline at end of file
| diff --git a/test/org/mockitousage/matchers/CapturingArgumentsTest.java b/test/org/mockitousage/matchers/CapturingArgumentsTest.java
index 44c8d87b50..d833e681e2 100644
--- a/test/org/mockitousage/matchers/CapturingArgumentsTest.java
+++ b/test/org/mockitousage/matchers/CapturingArgumentsTest.java
@@ -14,6 +14,7 @@
import org.mockitousage.IMethods;
import org.mockitoutil.TestBase;
+import java.util.ArrayList;
import java.util.List;
import static org.mockito.Matchers.any;
@@ -124,6 +125,18 @@ public void should_allow_assertions_on_captured_null() {
verify(emailService).sendEmailTo(argument.capture());
assertEquals(null, argument.getValue());
}
+
+ @Test
+ public void should_allow_construction_of_captor_for_parameterized_type_in_a_convenient_way() {
+ //the test passes if this expression compiles
+ ArgumentCaptor<List<Person>> argument = ArgumentCaptor.forClass(List.class);
+ }
+
+ @Test
+ public void should_allow_construction_of_captor_for_a_more_specific_type() {
+ //the test passes if this expression compiles
+ ArgumentCaptor<List> argument = ArgumentCaptor.forClass(ArrayList.class);
+ }
@Test
public void should_allow_capturing_for_stubbing() {
| train | train | 2015-04-16T19:22:45 | "2015-04-16T16:42:19Z" | bruceeddy | train |
mockito/mockito/187_202 | mockito/mockito | mockito/mockito/187 | mockito/mockito/202 | [
"keyword_pr_to_issue"
] | 4b5a03d1516778084e669f2f74ffbb9f9fc086f1 | 85fcbcb773ef8fd48105f18349d289b99591ba76 | [
"Hi,\n\nDo you have a JUnit test so that we could reproduce.\nAlso please see the [contributing guide](https://github.com/mockito/mockito/blob/master/CONTRIBUTING.md).\n",
"``` java\npublic class MockitoTest extends Mockito {\n public interface TestMock {\n public boolean m1();\n };\n\n @Test\n public void test() {\n TestMock test = mock(TestMock.class, new Answer() {\n @Override public Object answer(InvocationOnMock invocation) throws Throwable {\n return false;\n }\n });\n test.m1();\n verifyZeroInteractions(test);\n }\n}\n```\n",
"Hi, sorry for the late reply.\n\nThanks for the testcase, indeed we missed something there.\n\nFor reference the stacktrace is :\n\n```\njava.lang.ClassCastException: java.lang.Boolean cannot be cast to java.lang.String\n at org.mockitousage.bugs.ClassCastExOnVerifyZeroInteractionsTest$TestMock$$EnhancerByMockitoWithCGLIB$$91d883c5.toString(<generated>)\n at java.lang.String.valueOf(String.java:2847)\n at java.lang.StringBuilder.append(StringBuilder.java:128)\n at org.mockito.exceptions.Reporter.noMoreInteractionsWanted(Reporter.java:420)\n at org.mockito.internal.verification.NoMoreInteractions.verify(NoMoreInteractions.java:24)\n at org.mockito.internal.MockitoCore.verifyNoMoreInteractions(MockitoCore.java:113)\n at org.mockito.Mockito.verifyZeroInteractions(Mockito.java:1674)\n at org.mockitousage.bugs.ClassCastExOnVerifyZeroInteractionsTest.test(ClassCastExOnVerifyZeroInteractionsTest.java:23)\n```\n",
"Actually the usage report was improved to include the mock name, however in this usage the default answer always returns `false`. So when the String message is generated there's a CCE because the default answer returns a `boolean`.\n\nOn your side the workaround is to return valid values for these `Object` inherited methods.\n\nOn mockito side there should be two possible thing to do:\n- get the name safely without invoking `toString`\n- validate more aggressively answer's result\n",
"Hello, I've one doubt, can we do casting for mocking objects?. When I tried to do that I got \"java.lang.ClassCastException\"."
] | [] | "2015-04-19T18:42:31Z" | [
"bug"
] | java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.String | Exception throws on verifyZeroInteractions when using mock with default answer.
checked on versions 1.10.5-2.0.5
all ok on 1.9.5
| [
"src/org/mockito/exceptions/Reporter.java",
"src/org/mockito/internal/handler/MockHandlerImpl.java",
"src/org/mockito/internal/invocation/InvocationImpl.java",
"src/org/mockito/internal/stubbing/answers/AnswersValidator.java",
"src/org/mockito/invocation/Invocation.java"
] | [
"src/org/mockito/exceptions/Reporter.java",
"src/org/mockito/internal/handler/MockHandlerImpl.java",
"src/org/mockito/internal/invocation/InvocationImpl.java",
"src/org/mockito/internal/stubbing/answers/AnswersValidator.java",
"src/org/mockito/invocation/Invocation.java"
] | [
"test/org/mockito/exceptions/ReporterTest.java",
"test/org/mockito/internal/handler/MockHandlerImplTest.java",
"test/org/mockito/internal/stubbing/answers/AnswersValidatorTest.java",
"test/org/mockito/internal/verification/NoMoreInteractionsTest.java",
"test/org/mockitousage/bugs/ClassCastExOnVerifyZeroInteractionsTest.java",
"test/org/mockitousage/verification/DescriptiveMessagesWhenVerificationFailsTest.java"
] | diff --git a/src/org/mockito/exceptions/Reporter.java b/src/org/mockito/exceptions/Reporter.java
index 7ae75886c0..e0b1105daf 100644
--- a/src/org/mockito/exceptions/Reporter.java
+++ b/src/org/mockito/exceptions/Reporter.java
@@ -8,7 +8,13 @@
import org.mockito.exceptions.base.MockitoAssertionError;
import org.mockito.exceptions.base.MockitoException;
import org.mockito.exceptions.misusing.*;
-import org.mockito.exceptions.verification.*;
+import org.mockito.exceptions.verification.NeverWantedButInvoked;
+import org.mockito.exceptions.verification.NoInteractionsWanted;
+import org.mockito.exceptions.verification.SmartNullPointerException;
+import org.mockito.exceptions.verification.TooLittleActualInvocations;
+import org.mockito.exceptions.verification.TooManyActualInvocations;
+import org.mockito.exceptions.verification.VerificationInOrderFailure;
+import org.mockito.exceptions.verification.WantedButNotInvoked;
import org.mockito.internal.debugging.LocationImpl;
import org.mockito.internal.exceptions.MockitoLimitations;
import org.mockito.internal.exceptions.VerificationAwareInvocation;
@@ -22,6 +28,7 @@
import org.mockito.invocation.InvocationOnMock;
import org.mockito.invocation.Location;
import org.mockito.listeners.InvocationListener;
+import org.mockito.mock.MockName;
import org.mockito.mock.SerializableMode;
import java.lang.reflect.Field;
@@ -231,7 +238,7 @@ public void inOrderRequiresFamiliarMock() {
public void invalidUseOfMatchers(int expectedMatchersCount, List<LocalizedMatcher> recordedMatchers) {
throw new InvalidUseOfMatchersException(join(
"Invalid use of argument matchers!",
- expectedMatchersCount + " matchers expected, " + recordedMatchers.size()+ " recorded:" +
+ expectedMatchersCount + " matchers expected, " + recordedMatchers.size() + " recorded:" +
locationsOf(recordedMatchers),
"",
"This exception may occur if matchers are combined with raw values:",
@@ -387,7 +394,7 @@ public void tooManyActualInvocationsInOrder(int wantedCount, int actualCount, De
private String createTooLittleInvocationsMessage(org.mockito.internal.reporting.Discrepancy discrepancy, DescribedInvocation wanted,
Location lastActualInvocation) {
String ending =
- (lastActualInvocation != null)? lastActualInvocation + "\n" : "\n";
+ (lastActualInvocation != null) ? lastActualInvocation + "\n" : "\n";
String message = join(
wanted.toString(),
@@ -420,7 +427,7 @@ public void noMoreInteractionsWanted(Invocation undesired, List<VerificationAwar
throw new NoInteractionsWanted(join(
"No interactions wanted here:",
new LocationImpl(),
- "But found this interaction on mock '" + undesired.getMock() + "':",
+ "But found this interaction on mock '" + safelyGetMockName(undesired.getMock()) + "':",
undesired.getLocation(),
scenario
));
@@ -430,7 +437,7 @@ public void noMoreInteractionsWantedInOrder(Invocation undesired) {
throw new VerificationInOrderFailure(join(
"No interactions wanted here:",
new LocationImpl(),
- "But found this interaction on mock '" + undesired.getMock() + "':",
+ "But found this interaction on mock '" + safelyGetMockName(undesired.getMock()) + "':",
undesired.getLocation()
));
}
@@ -489,6 +496,18 @@ public void wrongTypeOfReturnValue(String expectedType, String actualType, Strin
));
}
+ public void wrongTypeReturnedByDefaultAnswer(Object mock, String expectedType, String actualType, String methodName) {
+ throw new WrongTypeOfReturnValue(join(
+ "Default answer returned a result with the wrong type:",
+ actualType + " cannot be returned by " + methodName + "()",
+ methodName + "() should return " + expectedType,
+ "",
+ "The default answer of " + safelyGetMockName(mock) + " that was configured on the mock is probably incorrectly implemented.",
+ ""
+ ));
+ }
+
+
public void wantedAtMostX(int maxNumberOfInvocations, int foundSize) {
throw new MockitoAssertionError(join("Wanted at most " + pluralize(maxNumberOfInvocations) + " but was " + foundSize));
}
@@ -641,7 +660,7 @@ public void atMostAndNeverShouldNotBeUsedWithTimeout() {
public void fieldInitialisationThrewException(Field field, Throwable details) {
throw new MockitoException(join(
- "Cannot instantiate @InjectMocks field named '" + field.getName() + "' of type '" + field.getType() + "'.",
+ "Cannot instantiate @InjectMocks field named '" + field.getName() + "' of type '" + field.getType() + "'.",
"You haven't provided the instance at field declaration so I tried to construct the instance.",
"However the constructor or the initialization block threw an exception : " + details.getMessage(),
""), details);
@@ -664,14 +683,21 @@ public void invocationListenerThrewException(InvocationListener listener, Throwa
public void cannotInjectDependency(Field field, Object matchingMock, Exception details) {
throw new MockitoException(join(
- "Mockito couldn't inject mock dependency '" + new MockUtil().getMockName(matchingMock) + "' on field ",
+ "Mockito couldn't inject mock dependency '" + safelyGetMockName(matchingMock) + "' on field ",
"'" + field + "'",
"whose type '" + field.getDeclaringClass().getCanonicalName() + "' was annotated by @InjectMocks in your test.",
- "Also I failed because: " + details.getCause().getMessage(),
+ "Also I failed because: " + exceptionCauseMessageIfAvailable(details),
""
), details);
}
+ private String exceptionCauseMessageIfAvailable(Exception details) {
+ if (details.getCause() == null) {
+ return details.getMessage();
+ }
+ return details.getCause().getMessage();
+ }
+
public void mockedTypeIsInconsistentWithDelegatedInstanceType(Class mockedType, Object delegatedInstance) {
throw new MockitoException(join(
"Mocked type must be the same as the type of your delegated instance.",
@@ -686,7 +712,7 @@ public void mockedTypeIsInconsistentWithDelegatedInstanceType(Class mockedType,
public void spyAndDelegateAreMutuallyExclusive() {
throw new MockitoException(join(
"Settings should not define a spy instance and a delegated instance at the same time."
- )) ;
+ ));
}
public void invalidArgumentRangeAtIdentityAnswerCreationTime() {
@@ -699,7 +725,7 @@ public void invalidArgumentRangeAtIdentityAnswerCreationTime() {
public int invalidArgumentPositionRangeAtInvocationTime(InvocationOnMock invocation, boolean willReturnLastParameter, int argumentIndex) {
throw new MockitoException(
join("Invalid argument index for the current invocation of method : ",
- " -> " + new MockUtil().getMockName(invocation.getMock()) + "." + invocation.getMethod().getName() + "()",
+ " -> " + safelyGetMockName(invocation.getMock()) + "." + invocation.getMethod().getName() + "()",
"",
(willReturnLastParameter ?
"Last parameter wanted" :
@@ -732,7 +758,7 @@ public void wrongTypeOfArgumentToReturn(InvocationOnMock invocation, String expe
throw new WrongTypeOfReturnValue(join(
"The argument of type '" + actualType.getSimpleName() + "' cannot be returned because the following ",
"method should return the type '" + expectedType + "'",
- " -> " + new MockUtil().getMockName(invocation.getMock()) + "." + invocation.getMethod().getName() + "()",
+ " -> " + safelyGetMockName(invocation.getMock()) + "." + invocation.getMethod().getName() + "()",
"",
"The reason for this error can be :",
"1. The wanted argument position is incorrect.",
@@ -765,28 +791,32 @@ public void serializableWontWorkForObjectsThatDontImplementSerializable(Class cl
""
));
}
-
+
public void delegatedMethodHasWrongReturnType(Method mockMethod, Method delegateMethod, Object mock, Object delegate) {
- throw new MockitoException(join(
- "Methods called on delegated instance must have compatible return types with the mock.",
- "When calling: " + mockMethod + " on mock: " + new MockUtil().getMockName(mock),
- "return type should be: " + mockMethod.getReturnType().getSimpleName() + ", but was: " + delegateMethod.getReturnType().getSimpleName(),
- "Check that the instance passed to delegatesTo() is of the correct type or contains compatible methods",
- "(delegate instance had type: " + delegate.getClass().getSimpleName() + ")"
- ));
- }
-
- public void delegatedMethodDoesNotExistOnDelegate(Method mockMethod, Object mock, Object delegate) {
- throw new MockitoException(join(
- "Methods called on mock must exist in delegated instance.",
- "When calling: " + mockMethod + " on mock: " + new MockUtil().getMockName(mock),
- "no such method was found.",
- "Check that the instance passed to delegatesTo() is of the correct type or contains compatible methods",
- "(delegate instance had type: " + delegate.getClass().getSimpleName() + ")"
- ));
- }
+ throw new MockitoException(join(
+ "Methods called on delegated instance must have compatible return types with the mock.",
+ "When calling: " + mockMethod + " on mock: " + safelyGetMockName(mock),
+ "return type should be: " + mockMethod.getReturnType().getSimpleName() + ", but was: " + delegateMethod.getReturnType().getSimpleName(),
+ "Check that the instance passed to delegatesTo() is of the correct type or contains compatible methods",
+ "(delegate instance had type: " + delegate.getClass().getSimpleName() + ")"
+ ));
+ }
+
+ public void delegatedMethodDoesNotExistOnDelegate(Method mockMethod, Object mock, Object delegate) {
+ throw new MockitoException(join(
+ "Methods called on mock must exist in delegated instance.",
+ "When calling: " + mockMethod + " on mock: " + safelyGetMockName(mock),
+ "no such method was found.",
+ "Check that the instance passed to delegatesTo() is of the correct type or contains compatible methods",
+ "(delegate instance had type: " + delegate.getClass().getSimpleName() + ")"
+ ));
+ }
public void usingConstructorWithFancySerializable(SerializableMode mode) {
throw new MockitoException("Mocks instantiated with constructor cannot be combined with " + mode + " serialization mode.");
}
+
+ private MockName safelyGetMockName(Object mock) {
+ return new MockUtil().getMockName(mock);
+ }
}
diff --git a/src/org/mockito/internal/handler/MockHandlerImpl.java b/src/org/mockito/internal/handler/MockHandlerImpl.java
index a49c1a98b7..00766a0d0d 100644
--- a/src/org/mockito/internal/handler/MockHandlerImpl.java
+++ b/src/org/mockito/internal/handler/MockHandlerImpl.java
@@ -10,7 +10,12 @@
import org.mockito.internal.invocation.MatchersBinder;
import org.mockito.internal.progress.MockingProgress;
import org.mockito.internal.progress.ThreadSafeMockingProgress;
-import org.mockito.internal.stubbing.*;
+import org.mockito.internal.stubbing.InvocationContainer;
+import org.mockito.internal.stubbing.InvocationContainerImpl;
+import org.mockito.internal.stubbing.OngoingStubbingImpl;
+import org.mockito.internal.stubbing.StubbedInvocationMatcher;
+import org.mockito.internal.stubbing.VoidMethodStubbableImpl;
+import org.mockito.internal.stubbing.answers.AnswersValidator;
import org.mockito.internal.verification.MockAwareVerificationMode;
import org.mockito.internal.verification.VerificationDataImpl;
import org.mockito.invocation.Invocation;
@@ -23,9 +28,8 @@
/**
* Invocation handler set on mock objects.
- *
- * @param <T>
- * type of mock object to handle
+ *
+ * @param <T> type of mock object to handle
*/
class MockHandlerImpl<T> implements InternalMockHandler<T> {
@@ -45,7 +49,7 @@ public MockHandlerImpl(MockCreationSettings mockSettings) {
}
public Object handle(Invocation invocation) throws Throwable {
- if (invocationContainerImpl.hasAnswersForStubbing()) {
+ if (invocationContainerImpl.hasAnswersForStubbing()) {
// stubbing voids with stubVoid() or doAnswer() style
InvocationMatcher invocationMatcher = matchersBinder.bindMatchers(
mockingProgress.getArgumentMatcherStorage(),
@@ -90,7 +94,8 @@ public Object handle(Invocation invocation) throws Throwable {
stubbedInvocation.captureArgumentsFrom(invocation);
return stubbedInvocation.answer(invocation);
} else {
- Object ret = mockSettings.getDefaultAnswer().answer(invocation);
+ Object ret = mockSettings.getDefaultAnswer().answer(invocation);
+ new AnswersValidator().validateDefaultAnswerReturnedValue(invocation, ret);
// redo setting invocation for potential stubbing in case of partial
// mocks / spies.
@@ -100,7 +105,7 @@ public Object handle(Invocation invocation) throws Throwable {
invocationContainerImpl.resetInvocationForPotentialStubbing(invocationMatcher);
return ret;
}
- }
+ }
public VoidMethodStubbable<T> voidMethodStubbable(T mock) {
return new VoidMethodStubbableImpl<T>(mock, invocationContainerImpl);
diff --git a/src/org/mockito/internal/invocation/InvocationImpl.java b/src/org/mockito/internal/invocation/InvocationImpl.java
index 19193fa165..dc77a57e25 100644
--- a/src/org/mockito/internal/invocation/InvocationImpl.java
+++ b/src/org/mockito/internal/invocation/InvocationImpl.java
@@ -105,6 +105,10 @@ public Object[] getRawArguments() {
return this.rawArguments;
}
+ public Class<?> getRawReturnType() {
+ return method.getReturnType();
+ }
+
public Object callRealMethod() throws Throwable {
if (method.isAbstract()) {
new Reporter().cannotCallAbstractRealMethod();
@@ -131,4 +135,4 @@ public boolean isIgnoredForVerification() {
public void ignoreForVerification() {
isIgnoredForVerification = true;
}
-}
\ No newline at end of file
+}
diff --git a/src/org/mockito/internal/stubbing/answers/AnswersValidator.java b/src/org/mockito/internal/stubbing/answers/AnswersValidator.java
index 57adb3881c..66bbf54c58 100644
--- a/src/org/mockito/internal/stubbing/answers/AnswersValidator.java
+++ b/src/org/mockito/internal/stubbing/answers/AnswersValidator.java
@@ -11,21 +11,21 @@
public class AnswersValidator {
private final Reporter reporter = new Reporter();
-
+
public void validate(Answer<?> answer, Invocation invocation) {
MethodInfo methodInfo = new MethodInfo(invocation);
if (answer instanceof ThrowsException) {
validateException((ThrowsException) answer, methodInfo);
}
-
+
if (answer instanceof Returns) {
validateReturnValue((Returns) answer, methodInfo);
}
-
+
if (answer instanceof DoesNothing) {
validateDoNothing((DoesNothing) answer, methodInfo);
}
-
+
if (answer instanceof CallsRealMethods) {
validateMockingConcreteClass((CallsRealMethods) answer, methodInfo);
}
@@ -42,8 +42,8 @@ private void validateReturnArgIdentity(ReturnsArgumentAt returnsArgumentAt, Invo
MethodInfo methodInfo = new MethodInfo(invocation);
if (!methodInfo.isValidReturnType(returnsArgumentAt.returnedTypeOnSignature(invocation))) {
new Reporter().wrongTypeOfArgumentToReturn(invocation, methodInfo.printMethodReturnType(),
- returnsArgumentAt.returnedTypeOnSignature(invocation),
- returnsArgumentAt.wantedArgumentPosition());
+ returnsArgumentAt.returnedTypeOnSignature(invocation),
+ returnsArgumentAt.wantedArgumentPosition());
}
}
@@ -64,10 +64,10 @@ private void validateReturnValue(Returns answer, MethodInfo methodInfo) {
if (methodInfo.isVoid()) {
reporter.cannotStubVoidMethodWithAReturnValue(methodInfo.getMethodName());
}
-
+
if (answer.returnsNull() && methodInfo.returnsPrimitive()) {
reporter.wrongTypeOfReturnValue(methodInfo.printMethodReturnType(), "null", methodInfo.getMethodName());
- }
+ }
if (!answer.returnsNull() && !methodInfo.isValidReturnType(answer.getReturnType())) {
reporter.wrongTypeOfReturnValue(methodInfo.printMethodReturnType(), answer.printReturnType(), methodInfo.getMethodName());
@@ -79,13 +79,24 @@ private void validateException(ThrowsException answer, MethodInfo methodInfo) {
if (throwable == null) {
reporter.cannotStubWithNullThrowable();
}
-
+
if (throwable instanceof RuntimeException || throwable instanceof Error) {
return;
}
-
+
if (!methodInfo.isValidException(throwable)) {
reporter.checkedExceptionInvalid(throwable);
}
}
-}
\ No newline at end of file
+
+ public void validateDefaultAnswerReturnedValue(Invocation invocation, Object returnedValue) {
+ MethodInfo methodInfo = new MethodInfo(invocation);
+ if (returnedValue != null && !methodInfo.isValidReturnType(returnedValue.getClass())) {
+ reporter.wrongTypeReturnedByDefaultAnswer(
+ invocation.getMock(),
+ methodInfo.printMethodReturnType(),
+ returnedValue.getClass().getSimpleName(),
+ methodInfo.getMethodName());
+ }
+ }
+}
diff --git a/src/org/mockito/invocation/Invocation.java b/src/org/mockito/invocation/Invocation.java
index 0146697309..7c1bdd5576 100644
--- a/src/org/mockito/invocation/Invocation.java
+++ b/src/org/mockito/invocation/Invocation.java
@@ -41,6 +41,14 @@ public interface Invocation extends InvocationOnMock, DescribedInvocation {
*/
Object[] getRawArguments();
+ /**
+ * Returns unprocessed arguments whereas {@link #getArguments()} returns
+ * arguments already processed (e.g. varargs expended, etc.).
+ *
+ * @return unprocessed arguments, exactly as provided to this invocation.
+ */
+ Class getRawReturnType();
+
/**
* Marks this invocation as verified so that it will not cause verification error at
* {@link org.mockito.Mockito#verifyNoMoreInteractions(Object...)}
| diff --git a/test/org/mockito/exceptions/ReporterTest.java b/test/org/mockito/exceptions/ReporterTest.java
index e006852784..3253ad819d 100644
--- a/test/org/mockito/exceptions/ReporterTest.java
+++ b/test/org/mockito/exceptions/ReporterTest.java
@@ -6,21 +6,81 @@
package org.mockito.exceptions;
import org.junit.Test;
+import org.mockito.Mockito;
import org.mockito.exceptions.base.MockitoException;
+import org.mockito.exceptions.verification.NoInteractionsWanted;
import org.mockito.exceptions.verification.TooLittleActualInvocations;
+import org.mockito.exceptions.verification.VerificationInOrderFailure;
+import org.mockito.internal.exceptions.VerificationAwareInvocation;
import org.mockito.internal.invocation.InvocationBuilder;
-import org.mockito.internal.reporting.*;
+import org.mockito.internal.stubbing.answers.Returns;
+import org.mockito.invocation.Invocation;
+import org.mockitousage.IMethods;
import org.mockitoutil.TestBase;
+import java.lang.reflect.Field;
+import java.util.Collections;
+
+import static org.mockito.Mockito.mock;
+
public class ReporterTest extends TestBase {
- @Test(expected=TooLittleActualInvocations.class)
- public void shouldLetPassingNullLastActualStackTrace() throws Exception {
+ @Test(expected = TooLittleActualInvocations.class)
+ public void should_let_passing_null_last_actual_stack_trace() throws Exception {
new Reporter().tooLittleActualInvocations(new org.mockito.internal.reporting.Discrepancy(1, 2), new InvocationBuilder().toInvocation(), null);
}
-
- @Test(expected=MockitoException.class)
- public void shouldThrowCorrectExceptionForNullInvocationListener() throws Exception {
- new Reporter().invocationListenerDoesNotAcceptNullParameters();
+
+ @Test(expected = MockitoException.class)
+ public void should_throw_correct_exception_for_null_invocation_listener() throws Exception {
+ new Reporter().invocationListenerDoesNotAcceptNullParameters();
+ }
+
+ @Test(expected = NoInteractionsWanted.class)
+ public void can_use_mock_name_even_when_mock_bogus_default_answer_and_when_reporting_no_more_interaction_wanted() throws Exception {
+ Invocation invocation_with_bogus_default_answer = new InvocationBuilder().mock(mock(IMethods.class, new Returns(false))).toInvocation();
+ new Reporter().noMoreInteractionsWanted(invocation_with_bogus_default_answer, Collections.<VerificationAwareInvocation>emptyList());
+ }
+
+ @Test(expected = VerificationInOrderFailure.class)
+ public void can_use_print_mock_name_even_when_mock_bogus_default_answer_and_when_reporting_no_more_interaction_wanted_in_order() throws Exception {
+ Invocation invocation_with_bogus_default_answer = new InvocationBuilder().mock(mock(IMethods.class, new Returns(false))).toInvocation();
+ new Reporter().noMoreInteractionsWantedInOrder(invocation_with_bogus_default_answer);
+ }
+
+ @Test(expected = MockitoException.class)
+ public void can_use_print_mock_name_even_when_mock_bogus_default_answer_and_when_reporting_invalid_argument_position() throws Exception {
+ Invocation invocation_with_bogus_default_answer = new InvocationBuilder().mock(mock(IMethods.class, new Returns(false))).toInvocation();
+ new Reporter().invalidArgumentPositionRangeAtInvocationTime(invocation_with_bogus_default_answer, true, 0);
+ }
+
+ @Test(expected = MockitoException.class)
+ public void can_use_print_mock_name_even_when_mock_bogus_default_answer_and_when_reporting_wrong_argument_to_return() throws Exception {
+ Invocation invocation_with_bogus_default_answer = new InvocationBuilder().mock(mock(IMethods.class, new Returns(false))).toInvocation();
+ new Reporter().wrongTypeOfArgumentToReturn(invocation_with_bogus_default_answer, "", String.class, 0);
+ }
+
+ @Test(expected = MockitoException.class)
+ public void can_use_print_mock_name_even_when_mock_bogus_default_answer_and_when_reporting_delegate_method_dont_exists() throws Exception {
+ Invocation dumb_invocation = new InvocationBuilder().toInvocation();
+ IMethods mock_with_bogus_default_answer = mock(IMethods.class, new Returns(false));
+ new Reporter().delegatedMethodDoesNotExistOnDelegate(dumb_invocation.getMethod(), mock_with_bogus_default_answer, String.class);
+ }
+
+ @Test(expected = MockitoException.class)
+ public void can_use_print_mock_name_even_when_mock_bogus_default_answer_and_when_reporting_delegate_method_has_wrong_return_type() throws Exception {
+ Invocation dumb_invocation = new InvocationBuilder().toInvocation();
+ IMethods mock_with_bogus_default_answer = mock(IMethods.class, new Returns(false));
+ new Reporter().delegatedMethodHasWrongReturnType(dumb_invocation.getMethod(), dumb_invocation.getMethod(), mock_with_bogus_default_answer, String.class);
}
+
+ @Test(expected = MockitoException.class)
+ public void can_use_print_mock_name_even_when_mock_bogus_default_answer_and_when_reporting_injection_failure() throws Exception {
+ IMethods mock_with_bogus_default_answer = mock(IMethods.class, new Returns(false));
+ new Reporter().cannotInjectDependency(someField(), mock_with_bogus_default_answer, new Exception());
+ }
+
+ private Field someField() {
+ return Mockito.class.getDeclaredFields()[0];
+ }
+
}
diff --git a/test/org/mockito/internal/handler/MockHandlerImplTest.java b/test/org/mockito/internal/handler/MockHandlerImplTest.java
index 8999fb4e55..104c4be6b5 100644
--- a/test/org/mockito/internal/handler/MockHandlerImplTest.java
+++ b/test/org/mockito/internal/handler/MockHandlerImplTest.java
@@ -8,6 +8,7 @@
import org.junit.Test;
import org.mockito.exceptions.base.MockitoException;
import org.mockito.exceptions.misusing.InvalidUseOfMatchersException;
+import org.mockito.exceptions.misusing.WrongTypeOfReturnValue;
import org.mockito.internal.creation.MockSettingsImpl;
import org.mockito.internal.invocation.InvocationBuilder;
import org.mockito.internal.invocation.InvocationImpl;
@@ -16,6 +17,7 @@
import org.mockito.internal.progress.ArgumentMatcherStorage;
import org.mockito.internal.stubbing.InvocationContainerImpl;
import org.mockito.internal.stubbing.StubbedInvocationMatcher;
+import org.mockito.internal.stubbing.answers.Returns;
import org.mockito.internal.verification.VerificationModeFactory;
import org.mockito.invocation.Invocation;
import org.mockito.listeners.InvocationListener;
@@ -29,79 +31,88 @@
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
-@SuppressWarnings({ "unchecked", "serial" })
+@SuppressWarnings({"unchecked", "serial"})
public class MockHandlerImplTest extends TestBase {
- private StubbedInvocationMatcher stubbedInvocationMatcher = mock(StubbedInvocationMatcher.class);
- private Invocation invocation = mock(InvocationImpl.class);
+ private StubbedInvocationMatcher stubbedInvocationMatcher = mock(StubbedInvocationMatcher.class);
+ private Invocation invocation = mock(InvocationImpl.class);
- @Test
- public void shouldRemoveVerificationModeEvenWhenInvalidMatchers() throws Throwable {
- // given
- Invocation invocation = new InvocationBuilder().toInvocation();
- @SuppressWarnings("rawtypes")
+ @Test
+ public void should_remove_verification_mode_even_when_invalid_matchers() throws Throwable {
+ // given
+ Invocation invocation = new InvocationBuilder().toInvocation();
+ @SuppressWarnings("rawtypes")
MockHandlerImpl<?> handler = new MockHandlerImpl(new MockSettingsImpl());
- handler.mockingProgress.verificationStarted(VerificationModeFactory.atLeastOnce());
- handler.matchersBinder = new MatchersBinder() {
- public InvocationMatcher bindMatchers(ArgumentMatcherStorage argumentMatcherStorage, Invocation invocation) {
- throw new InvalidUseOfMatchersException();
- }
- };
-
- try {
- // when
- handler.handle(invocation);
-
- // then
- fail();
- } catch (InvalidUseOfMatchersException e) {
- }
-
- assertNull(handler.mockingProgress.pullVerificationMode());
- }
-
-
-
-
- @Test(expected = MockitoException.class)
- public void shouldThrowMockitoExceptionWhenInvocationHandlerThrowsAnything() throws Throwable {
- // given
- InvocationListener throwingListener = mock(InvocationListener.class);
- doThrow(new Throwable()).when(throwingListener).reportInvocation(any(MethodInvocationReport.class));
- MockHandlerImpl<?> handler = createCorrectlyStubbedHandler(throwingListener);
-
- // when
- handler.handle(invocation);
- }
-
-
-
- private MockHandlerImpl<?> createCorrectlyStubbedHandler(InvocationListener throwingListener) {
- MockHandlerImpl<?> handler = createHandlerWithListeners(throwingListener);
- stubOrdinaryInvocationWithGivenReturnValue(handler);
- return handler;
- }
-
- private void stubOrdinaryInvocationWithGivenReturnValue(MockHandlerImpl<?> handler) {
- stubOrdinaryInvocationWithInvocationMatcher(handler, stubbedInvocationMatcher);
- }
-
-
-
- private void stubOrdinaryInvocationWithInvocationMatcher(MockHandlerImpl<?> handler, StubbedInvocationMatcher value) {
- handler.invocationContainerImpl = mock(InvocationContainerImpl.class);
- given(handler.invocationContainerImpl.findAnswerFor(any(InvocationImpl.class))).willReturn(value);
- }
-
-
-
-
- private MockHandlerImpl<?> createHandlerWithListeners(InvocationListener... listener) {
- @SuppressWarnings("rawtypes")
+ handler.mockingProgress.verificationStarted(VerificationModeFactory.atLeastOnce());
+ handler.matchersBinder = new MatchersBinder() {
+ public InvocationMatcher bindMatchers(ArgumentMatcherStorage argumentMatcherStorage, Invocation invocation) {
+ throw new InvalidUseOfMatchersException();
+ }
+ };
+
+ try {
+ // when
+ handler.handle(invocation);
+
+ // then
+ fail();
+ } catch (InvalidUseOfMatchersException ignored) {
+ }
+
+ assertNull(handler.mockingProgress.pullVerificationMode());
+ }
+
+
+ @Test(expected = MockitoException.class)
+ public void should_throw_mockito_exception_when_invocation_handler_throws_anything() throws Throwable {
+ // given
+ InvocationListener throwingListener = mock(InvocationListener.class);
+ doThrow(new Throwable()).when(throwingListener).reportInvocation(any(MethodInvocationReport.class));
+ MockHandlerImpl<?> handler = create_correctly_stubbed_handler(throwingListener);
+
+ // when
+ handler.handle(invocation);
+ }
+
+ @Test(expected = WrongTypeOfReturnValue.class)
+ public void should_report_bogus_default_answer() throws Throwable {
+ MockSettingsImpl mockSettings = mock(MockSettingsImpl.class);
+ MockHandlerImpl<?> handler = new MockHandlerImpl(mockSettings);
+ given(mockSettings.getDefaultAnswer()).willReturn(new Returns(AWrongType.WRONG_TYPE));
+
+ @SuppressWarnings("unused") // otherwise cast is not done
+ String there_should_not_be_a_CCE_here = (String) handler.handle(
+ new InvocationBuilder().method(Object.class.getDeclaredMethod("toString")).toInvocation()
+ );
+ }
+
+ private MockHandlerImpl<?> create_correctly_stubbed_handler(InvocationListener throwingListener) {
+ MockHandlerImpl<?> handler = create_handler_with_listeners(throwingListener);
+ stub_ordinary_invocation_with_given_return_value(handler);
+ return handler;
+ }
+
+ private void stub_ordinary_invocation_with_given_return_value(MockHandlerImpl<?> handler) {
+ stub_ordinary_invocation_with_invocation_matcher(handler, stubbedInvocationMatcher);
+ }
+
+
+ private void stub_ordinary_invocation_with_invocation_matcher(MockHandlerImpl<?> handler, StubbedInvocationMatcher value) {
+ handler.invocationContainerImpl = mock(InvocationContainerImpl.class);
+ given(handler.invocationContainerImpl.findAnswerFor(any(InvocationImpl.class))).willReturn(value);
+ }
+
+
+ private MockHandlerImpl<?> create_handler_with_listeners(InvocationListener... listener) {
+ @SuppressWarnings("rawtypes")
MockHandlerImpl<?> handler = new MockHandlerImpl(mock(MockSettingsImpl.class));
- handler.matchersBinder = mock(MatchersBinder.class);
- given(handler.getMockSettings().getInvocationListeners()).willReturn(Arrays.asList(listener));
- return handler;
- }
+ handler.matchersBinder = mock(MatchersBinder.class);
+ given(handler.getMockSettings().getInvocationListeners()).willReturn(Arrays.asList(listener));
+ return handler;
+ }
+
+ private static class AWrongType {
+ public static final AWrongType WRONG_TYPE = new AWrongType();
+ }
}
diff --git a/test/org/mockito/internal/stubbing/answers/AnswersValidatorTest.java b/test/org/mockito/internal/stubbing/answers/AnswersValidatorTest.java
index 914535fbb8..04b5917575 100644
--- a/test/org/mockito/internal/stubbing/answers/AnswersValidatorTest.java
+++ b/test/org/mockito/internal/stubbing/answers/AnswersValidatorTest.java
@@ -1,7 +1,7 @@
-/*
- * Copyright (c) 2007 Mockito contributors
- * This program is made available under the terms of the MIT License.
- */
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
package org.mockito.internal.stubbing.answers;
import org.junit.Test;
@@ -30,7 +30,7 @@ public void should_validate_null_throwable() throws Throwable {
try {
validator.validate(new ThrowsException(null), new InvocationBuilder().toInvocation());
fail();
- } catch (MockitoException e) {}
+ } catch (MockitoException expected) {}
}
@Test
@@ -42,28 +42,28 @@ public void should_pass_proper_checked_exception() throws Throwable {
public void should_fail_invalid_checked_exception() throws Throwable {
validator.validate(new ThrowsException(new IOException()), invocation);
}
-
+
@Test
public void should_pass_RuntimeExceptions() throws Throwable {
validator.validate(new ThrowsException(new Error()), invocation);
validator.validate(new ThrowsException(new RuntimeException()), invocation);
}
-
+
@Test(expected = MockitoException.class)
public void should_fail_when_return_Value_is_set_for_void_method() throws Throwable {
validator.validate(new Returns("one"), new InvocationBuilder().method("voidMethod").toInvocation());
}
-
+
@Test(expected = MockitoException.class)
public void should_fail_when_non_void_method_does_nothing() throws Throwable {
validator.validate(new DoesNothing(), new InvocationBuilder().simpleMethod().toInvocation());
}
-
+
@Test
public void should_allow_void_return_for_void_method() throws Throwable {
validator.validate(new DoesNothing(), new InvocationBuilder().method("voidMethod").toInvocation());
}
-
+
@Test
public void should_allow_correct_type_of_return_value() throws Throwable {
validator.validate(new Returns("one"), new InvocationBuilder().simpleMethod().toInvocation());
@@ -75,12 +75,12 @@ public void should_allow_correct_type_of_return_value() throws Throwable {
validator.validate(new Returns(null), new InvocationBuilder().method("objectReturningMethodNoArgs").toInvocation());
validator.validate(new Returns(1), new InvocationBuilder().method("objectReturningMethodNoArgs").toInvocation());
}
-
+
@Test(expected = MockitoException.class)
public void should_fail_on_return_type_mismatch() throws Throwable {
validator.validate(new Returns("String"), new InvocationBuilder().method("booleanReturningMethod").toInvocation());
}
-
+
@Test(expected = MockitoException.class)
public void should_fail_on_wrong_primitive() throws Throwable {
validator.validate(new Returns(1), new InvocationBuilder().method("doubleReturningMethod").toInvocation());
@@ -90,7 +90,7 @@ public void should_fail_on_wrong_primitive() throws Throwable {
public void should_fail_on_null_with_primitive() throws Throwable {
validator.validate(new Returns(null), new InvocationBuilder().method("booleanReturningMethod").toInvocation());
}
-
+
@Test
public void should_fail_when_calling_real_method_on_interface() throws Throwable {
//given
@@ -100,9 +100,9 @@ public void should_fail_when_calling_real_method_on_interface() throws Throwable
validator.validate(new CallsRealMethods(), invocationOnInterface);
//then
fail();
- } catch (MockitoException e) {}
+ } catch (MockitoException expected) {}
}
-
+
@Test
public void should_be_OK_when_calling_real_method_on_concrete_class() throws Throwable {
//given
@@ -194,4 +194,31 @@ public void should_fail_if_argument_type_of_signature_is_incompatible_with_retur
}
}
-}
\ No newline at end of file
+ @Test
+ public void should_fail_if_returned_value_of_answer_is_incompatible_with_return_type() throws Throwable {
+ try {
+ validator.validateDefaultAnswerReturnedValue(
+ new InvocationBuilder().method("toString").toInvocation(),
+ AWrongType.WRONG_TYPE
+ );
+ fail();
+ } catch (WrongTypeOfReturnValue e) {
+ assertThat(e.getMessage())
+ .containsIgnoringCase("Default answer returned a result with the wrong type")
+ .containsIgnoringCase("AWrongType cannot be returned by toString()")
+ .containsIgnoringCase("toString() should return String");
+ }
+ }
+
+ @Test
+ public void should_not_fail_if_returned_value_of_answer_is_null() throws Throwable {
+ validator.validateDefaultAnswerReturnedValue(
+ new InvocationBuilder().method("toString").toInvocation(),
+ null
+ );
+ }
+
+ private static class AWrongType {
+ public static final AWrongType WRONG_TYPE = new AWrongType();
+ }
+}
diff --git a/test/org/mockito/internal/verification/NoMoreInteractionsTest.java b/test/org/mockito/internal/verification/NoMoreInteractionsTest.java
index 4b52575d6e..e8c9303075 100644
--- a/test/org/mockito/internal/verification/NoMoreInteractionsTest.java
+++ b/test/org/mockito/internal/verification/NoMoreInteractionsTest.java
@@ -1,35 +1,37 @@
-/*
- * Copyright (c) 2007 Mockito contributors
- * This program is made available under the terms of the MIT License.
- */
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
package org.mockito.internal.verification;
-import static java.util.Arrays.*;
-
-import org.fest.assertions.Assertions;
+import org.fest.assertions.Assertions;
import org.junit.Test;
-import org.mockito.exceptions.verification.NoInteractionsWanted;
+import org.mockito.exceptions.verification.NoInteractionsWanted;
import org.mockito.exceptions.verification.VerificationInOrderFailure;
-import org.mockito.internal.creation.MockSettingsImpl;
+import org.mockito.internal.creation.MockSettingsImpl;
import org.mockito.internal.invocation.InvocationBuilder;
-import org.mockito.internal.invocation.InvocationMatcher;
-import org.mockito.internal.progress.ThreadSafeMockingProgress;
-import org.mockito.internal.stubbing.InvocationContainerImpl;
+import org.mockito.internal.invocation.InvocationMatcher;
+import org.mockito.internal.progress.ThreadSafeMockingProgress;
+import org.mockito.internal.stubbing.InvocationContainerImpl;
import org.mockito.internal.verification.api.VerificationDataInOrderImpl;
import org.mockito.invocation.Invocation;
+import org.mockitousage.IMethods;
import org.mockitoutil.TestBase;
+import static java.util.Arrays.asList;
+import static org.mockito.Mockito.mock;
+
public class NoMoreInteractionsTest extends TestBase {
InOrderContextImpl context = new InOrderContextImpl();
-
+
@Test
public void shouldVerifyInOrder() {
//given
NoMoreInteractions n = new NoMoreInteractions();
Invocation i = new InvocationBuilder().toInvocation();
assertFalse(context.isVerified(i));
-
+
try {
//when
n.verifyInOrder(new VerificationDataInOrderImpl(context, asList(i), null));
@@ -37,7 +39,7 @@ public void shouldVerifyInOrder() {
fail();
} catch(VerificationInOrderFailure e) {}
}
-
+
@Test
public void shouldVerifyInOrderAndPass() {
//given
@@ -45,12 +47,12 @@ public void shouldVerifyInOrderAndPass() {
Invocation i = new InvocationBuilder().toInvocation();
context.markVerified(i);
assertTrue(context.isVerified(i));
-
+
//when
n.verifyInOrder(new VerificationDataInOrderImpl(context, asList(i), null));
//then no exception is thrown
}
-
+
@Test
public void shouldVerifyInOrderMultipleInvoctions() {
//given
@@ -77,43 +79,43 @@ public void shouldVerifyInOrderMultipleInvoctionsAndThrow() {
n.verifyInOrder(new VerificationDataInOrderImpl(context, asList(i, i2), null));
fail();
} catch (VerificationInOrderFailure e) {}
- }
-
- @Test
- public void noMoreInteractionsExceptionMessageShouldDescribeMock() {
- //given
- NoMoreInteractions n = new NoMoreInteractions();
- String mock = "a mock";
- InvocationMatcher i = new InvocationBuilder().mock(mock).toInvocationMatcher();
-
- InvocationContainerImpl invocations =
- new InvocationContainerImpl(new ThreadSafeMockingProgress(), new MockSettingsImpl());
- invocations.setInvocationForPotentialStubbing(i);
-
- try {
- //when
- n.verify(new VerificationDataImpl(invocations, null));
- //then
- fail();
- } catch (NoInteractionsWanted e) {
- Assertions.assertThat(e.toString()).contains(mock.toString());
- }
- }
-
- @Test
- public void noMoreInteractionsInOrderExceptionMessageShouldDescribeMock() {
- //given
- NoMoreInteractions n = new NoMoreInteractions();
- String mock = "a mock";
- Invocation i = new InvocationBuilder().mock(mock).toInvocation();
-
- try {
- //when
- n.verifyInOrder(new VerificationDataInOrderImpl(context, asList(i), null));
- //then
- fail();
- } catch (VerificationInOrderFailure e) {
- Assertions.assertThat(e.toString()).contains(mock.toString());
- }
}
-}
\ No newline at end of file
+
+ @Test
+ public void noMoreInteractionsExceptionMessageShouldDescribeMock() {
+ //given
+ NoMoreInteractions n = new NoMoreInteractions();
+ IMethods mock = mock(IMethods.class, "a mock");
+ InvocationMatcher i = new InvocationBuilder().mock(mock).toInvocationMatcher();
+
+ InvocationContainerImpl invocations =
+ new InvocationContainerImpl(new ThreadSafeMockingProgress(), new MockSettingsImpl());
+ invocations.setInvocationForPotentialStubbing(i);
+
+ try {
+ //when
+ n.verify(new VerificationDataImpl(invocations, null));
+ //then
+ fail();
+ } catch (NoInteractionsWanted e) {
+ Assertions.assertThat(e.toString()).contains(mock.toString());
+ }
+ }
+
+ @Test
+ public void noMoreInteractionsInOrderExceptionMessageShouldDescribeMock() {
+ //given
+ NoMoreInteractions n = new NoMoreInteractions();
+ IMethods mock = mock(IMethods.class, "a mock");
+ Invocation i = new InvocationBuilder().mock(mock).toInvocation();
+
+ try {
+ //when
+ n.verifyInOrder(new VerificationDataInOrderImpl(context, asList(i), null));
+ //then
+ fail();
+ } catch (VerificationInOrderFailure e) {
+ Assertions.assertThat(e.toString()).contains(mock.toString());
+ }
+ }
+}
diff --git a/test/org/mockitousage/bugs/ClassCastExOnVerifyZeroInteractionsTest.java b/test/org/mockitousage/bugs/ClassCastExOnVerifyZeroInteractionsTest.java
new file mode 100644
index 0000000000..6b6cc85395
--- /dev/null
+++ b/test/org/mockitousage/bugs/ClassCastExOnVerifyZeroInteractionsTest.java
@@ -0,0 +1,38 @@
+package org.mockitousage.bugs;
+
+import org.junit.Test;
+import org.mockito.exceptions.misusing.WrongTypeOfReturnValue;
+import org.mockito.exceptions.verification.NoInteractionsWanted;
+import org.mockito.invocation.InvocationOnMock;
+import org.mockito.stubbing.Answer;
+
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verifyZeroInteractions;
+
+public class ClassCastExOnVerifyZeroInteractionsTest {
+ public interface TestMock {
+ boolean m1();
+ }
+
+ @Test(expected = NoInteractionsWanted.class)
+ public void should_not_throw_ClassCastException_when_mock_verification_fails() {
+ TestMock test = mock(TestMock.class, new Answer() {
+ public Object answer(InvocationOnMock invocation) throws Throwable {
+ return false;
+ }
+ });
+ test.m1();
+ verifyZeroInteractions(test);
+ }
+
+ @Test(expected = WrongTypeOfReturnValue.class)
+ public void should_report_bogus_default_answer() throws Exception {
+ TestMock test = mock(TestMock.class, new Answer() {
+ public Object answer(InvocationOnMock invocation) throws Throwable {
+ return false;
+ }
+ });
+
+ test.toString();
+ }
+}
diff --git a/test/org/mockitousage/verification/DescriptiveMessagesWhenVerificationFailsTest.java b/test/org/mockitousage/verification/DescriptiveMessagesWhenVerificationFailsTest.java
index 44a074ef5c..f30540edbf 100644
--- a/test/org/mockitousage/verification/DescriptiveMessagesWhenVerificationFailsTest.java
+++ b/test/org/mockitousage/verification/DescriptiveMessagesWhenVerificationFailsTest.java
@@ -33,7 +33,7 @@ public class DescriptiveMessagesWhenVerificationFailsTest extends TestBase {
@Before
public void setup() {
- mock = Mockito.mock(IMethods.class);
+ mock = Mockito.mock(IMethods.class, "iMethods");
}
@Test
@@ -85,8 +85,8 @@ public void should_print_actual_and_wanted_in_line() {
"iMethods.varargs(1, 1000);";
assertContains(wanted, e.getMessage());
-
- String actual =
+
+ String actual =
"\n" +
"Actual invocation has different arguments:" +
"\n" +
@@ -95,7 +95,7 @@ public void should_print_actual_and_wanted_in_line() {
assertContains(actual, e.getMessage());
}
}
-
+
@Test
public void should_print_actual_and_wanted_in_multiple_lines() {
mock.varargs("this is very long string", "this is another very long string");
@@ -296,11 +296,11 @@ public void should_print_null_arguments() throws Exception {
assertContains("simpleMethod(null, null);", e.getMessage());
}
}
-
+
@Test
public void should_say_never_wanted_but_invoked() throws Exception {
mock.simpleMethod(1);
-
+
verify(mock, never()).simpleMethod(2);
try {
verify(mock, never()).simpleMethod(1);
@@ -310,12 +310,12 @@ public void should_say_never_wanted_but_invoked() throws Exception {
assertContains("But invoked here:", e.getMessage());
}
}
-
+
@Test
public void should_show_right_actual_method() throws Exception {
mock.simpleMethod(9191);
mock.simpleMethod("foo");
-
+
try {
verify(mock).simpleMethod("bar");
fail();
@@ -326,11 +326,11 @@ public void should_show_right_actual_method() throws Exception {
}
@Mock private IMethods iHavefunkyName;
-
+
@Test
public void should_print_field_name_when_annotations_used() throws Exception {
iHavefunkyName.simpleMethod(10);
-
+
try {
verify(iHavefunkyName).simpleMethod(20);
fail();
@@ -339,12 +339,12 @@ public void should_print_field_name_when_annotations_used() throws Exception {
assertContains("iHavefunkyName.simpleMethod(10)", e.getMessage());
}
}
-
+
@Test
public void should_print_interactions_on_mock_when_ordinary_verification_fail() throws Exception {
mock.otherMethod();
mock.booleanReturningMethod();
-
+
try {
verify(mock).simpleMethod();
fail();
@@ -353,8 +353,8 @@ public void should_print_interactions_on_mock_when_ordinary_verification_fail()
}
}
- @Mock private IMethods veeeeeeeeeeeeeeeeeeeeeeeerylongNameMock;
-
+ @Mock private IMethods veeeeeeeeeeeeeeeeeeeeeeeerylongNameMock;
+
@Test
public void should_never_break_method_string_when_no_args_in_method() throws Exception {
try {
@@ -430,5 +430,4 @@ public void test2() {
public interface AnInterface {
void foo(int i);
}
-
-}
\ No newline at end of file
+}
| train | train | 2015-04-17T11:55:17 | "2015-03-24T13:14:54Z" | mktitov | train |
mockito/mockito/197_207 | mockito/mockito | mockito/mockito/197 | mockito/mockito/207 | [
"keyword_pr_to_issue"
] | d30450fa1172d79cc051b2fe8064744c2ac7a003 | 45aa5bf2c266268d209aabf17053e975e2634da1 | [
"Well spotted, thx\n",
"I can try to fix that, but need to know what exactly is the issue here:\nShould negative values in after method be forbidden and trigger exception to be thrown? or maybe negatives are allowed here (negative value means - immediately, pretty much it should behave like after(0) )?\n",
"I would vote for an IllegalArgumentException being thrown.\n",
"The same is happening for _timeout_ method:\ne.g. \n\n```\n SomeClazz mock = Mockito.mock(SomeClazz.class);\n Mockito.verify(mock, timeout(-100)).someMethod(); //passes, which is incorrect\n```\n\nIf method was invoked, then it passes, but this negative timeout is at least confusing:\n\n```\n SomeClazz mock = Mockito.mock(SomeClazz.class);\n mock.someMethod();\n Mockito.verify(mock, timeout(-100)).someMethod(); //passes\n```\n"
] | [] | "2015-05-08T19:15:59Z" | [
"bug"
] | Mockito.after() method accepts negative timeperiods and subsequent verifications always pass | e.g.
```
Runnable runnable = Mockito.mock(Runnable.class);
Mockito.verify(runnable, Mockito.never()).run(); // passes as expected
Mockito.verify(runnable, Mockito.after(1000).never()).run(); // passes as expected
Mockito.verify(runnable, Mockito.after(-1000).atLeastOnce()).run(); // passes incorrectly
```
| [
"src/org/mockito/exceptions/Reporter.java",
"src/org/mockito/internal/util/Timer.java",
"src/org/mockito/internal/verification/VerificationOverTimeImpl.java",
"src/org/mockito/verification/After.java",
"src/org/mockito/verification/Timeout.java"
] | [
"src/org/mockito/exceptions/Reporter.java",
"src/org/mockito/internal/util/Timer.java",
"src/org/mockito/internal/verification/VerificationOverTimeImpl.java",
"src/org/mockito/verification/After.java",
"src/org/mockito/verification/Timeout.java"
] | [
"test/org/mockito/internal/util/TimerTest.java",
"test/org/mockito/verification/NegativeDurationTest.java",
"test/org/mockito/verification/TimeoutTest.java"
] | diff --git a/src/org/mockito/exceptions/Reporter.java b/src/org/mockito/exceptions/Reporter.java
index e0b1105daf..6e0b3bd157 100644
--- a/src/org/mockito/exceptions/Reporter.java
+++ b/src/org/mockito/exceptions/Reporter.java
@@ -816,6 +816,15 @@ public void usingConstructorWithFancySerializable(SerializableMode mode) {
throw new MockitoException("Mocks instantiated with constructor cannot be combined with " + mode + " serialization mode.");
}
+ public void cannotCreateTimerWithNegativeDurationTime(long durationMillis) {
+ throw new FriendlyReminderException(join("",
+ "Don't panic! I'm just a friendly reminder!",
+ "It is impossible for time to go backward, therefore...",
+ "You cannot put negative value of duration: (" + durationMillis + ")",
+ "as argument of timer methods (after(), timeout())",
+ ""));
+ }
+
private MockName safelyGetMockName(Object mock) {
return new MockUtil().getMockName(mock);
}
diff --git a/src/org/mockito/internal/util/Timer.java b/src/org/mockito/internal/util/Timer.java
index b71e4fdd8f..9f4829749f 100644
--- a/src/org/mockito/internal/util/Timer.java
+++ b/src/org/mockito/internal/util/Timer.java
@@ -1,11 +1,14 @@
package org.mockito.internal.util;
+import org.mockito.exceptions.Reporter;
+
public class Timer {
private final long durationMillis;
private long startTime = -1;
public Timer(long durationMillis) {
+ validateInput(durationMillis);
this.durationMillis = durationMillis;
}
@@ -23,4 +26,14 @@ public boolean isCounting() {
public void start() {
startTime = System.currentTimeMillis();
}
+
+ private void validateInput(long durationMillis) {
+ if (durationMillis < 0) {
+ new Reporter().cannotCreateTimerWithNegativeDurationTime(durationMillis);
+ }
+ }
+
+ public long duration() {
+ return durationMillis;
+ }
}
diff --git a/src/org/mockito/internal/verification/VerificationOverTimeImpl.java b/src/org/mockito/internal/verification/VerificationOverTimeImpl.java
index 4ea2463adc..e719cb402b 100644
--- a/src/org/mockito/internal/verification/VerificationOverTimeImpl.java
+++ b/src/org/mockito/internal/verification/VerificationOverTimeImpl.java
@@ -17,7 +17,6 @@
public class VerificationOverTimeImpl implements VerificationMode {
private final long pollingPeriodMillis;
- private final long durationMillis;
private final VerificationMode delegate;
private final boolean returnOnSuccess;
private final Timer timer;
@@ -34,14 +33,13 @@ public class VerificationOverTimeImpl implements VerificationMode {
* {@link org.mockito.verification.VerificationAfterDelay}).
*/
public VerificationOverTimeImpl(long pollingPeriodMillis, long durationMillis, VerificationMode delegate, boolean returnOnSuccess) {
- this(pollingPeriodMillis, durationMillis, delegate, returnOnSuccess, new Timer(durationMillis));
+ this(pollingPeriodMillis, delegate, returnOnSuccess, new Timer(durationMillis));
}
/**
* Create this verification mode, to be used to verify invocation ongoing data later.
*
* @param pollingPeriodMillis The frequency to poll delegate.verify(), to check whether the delegate has been satisfied
- * @param durationMillis The max time to wait (in millis) for the delegate verification mode to be satisfied
* @param delegate The verification mode to delegate overall success or failure to
* @param returnOnSuccess Whether to immediately return successfully once the delegate is satisfied (as in
* {@link org.mockito.verification.VerificationWithTimeout}, or to only return once
@@ -49,9 +47,8 @@ public VerificationOverTimeImpl(long pollingPeriodMillis, long durationMillis, V
* {@link org.mockito.verification.VerificationAfterDelay}).
* @param timer Checker of whether the duration of the verification is still acceptable
*/
- public VerificationOverTimeImpl(long pollingPeriodMillis, long durationMillis, VerificationMode delegate, boolean returnOnSuccess, Timer timer) {
+ public VerificationOverTimeImpl(long pollingPeriodMillis, VerificationMode delegate, boolean returnOnSuccess, Timer timer) {
this.pollingPeriodMillis = pollingPeriodMillis;
- this.durationMillis = durationMillis;
this.delegate = delegate;
this.returnOnSuccess = returnOnSuccess;
this.timer = timer;
@@ -111,24 +108,15 @@ protected boolean canRecoverFromFailure(VerificationMode verificationMode) {
return !(verificationMode instanceof AtMost || verificationMode instanceof NoMoreInteractions);
}
+ public VerificationOverTimeImpl copyWithVerificationMode(VerificationMode verificationMode) {
+ return new VerificationOverTimeImpl(pollingPeriodMillis, timer.duration(), verificationMode, returnOnSuccess);
+ }
+
private void sleep(long sleep) {
try {
Thread.sleep(sleep);
} catch (InterruptedException ie) {
- // oups. not much luck.
+ throw new RuntimeException("Thread sleep has been interrupted", ie);
}
}
-
- public long getPollingPeriod() {
- return pollingPeriodMillis;
- }
-
- public long getDuration() {
- return durationMillis;
- }
-
- public VerificationMode getDelegate() {
- return delegate;
- }
-
}
diff --git a/src/org/mockito/verification/After.java b/src/org/mockito/verification/After.java
index 07d312232a..8d203581b7 100644
--- a/src/org/mockito/verification/After.java
+++ b/src/org/mockito/verification/After.java
@@ -20,13 +20,17 @@ public After(long delayMillis, VerificationMode verificationMode) {
this(10, delayMillis, verificationMode);
}
- public After(long pollingPeriod, long delayMillis, VerificationMode verificationMode) {
- super(new VerificationOverTimeImpl(pollingPeriod, delayMillis, verificationMode, false));
+ After(long pollingPeriod, long delayMillis, VerificationMode verificationMode) {
+ this(new VerificationOverTimeImpl(pollingPeriod, delayMillis, verificationMode, false));
}
-
+
+ After(VerificationOverTimeImpl verificationOverTime) {
+ super(verificationOverTime);
+ }
+
@Override
protected VerificationMode copySelfWithNewVerificationMode(VerificationMode verificationMode) {
- return new After(wrappedVerification.getPollingPeriod(), wrappedVerification.getDuration(), verificationMode);
+ return new After(wrappedVerification.copyWithVerificationMode(verificationMode));
}
}
diff --git a/src/org/mockito/verification/Timeout.java b/src/org/mockito/verification/Timeout.java
index d8e87ba448..9cfcdad69b 100644
--- a/src/org/mockito/verification/Timeout.java
+++ b/src/org/mockito/verification/Timeout.java
@@ -29,21 +29,25 @@ public Timeout(long millis, VerificationMode delegate) {
* See the javadoc for {@link VerificationWithTimeout}
*/
Timeout(long pollingPeriodMillis, long millis, VerificationMode delegate) {
- super(new VerificationOverTimeImpl(pollingPeriodMillis, millis, delegate, true));
+ this(new VerificationOverTimeImpl(pollingPeriodMillis, millis, delegate, true));
}
/**
* See the javadoc for {@link VerificationWithTimeout}
*/
- Timeout(long pollingPeriodMillis, long millis, VerificationMode delegate, Timer timer) {
- super(new VerificationOverTimeImpl(pollingPeriodMillis, millis, delegate, true, timer));
+ Timeout(long pollingPeriodMillis, VerificationMode delegate, Timer timer) {
+ this(new VerificationOverTimeImpl(pollingPeriodMillis, delegate, true, timer));
}
-
+
+ Timeout(VerificationOverTimeImpl verificationOverTime) {
+ super(verificationOverTime);
+ }
+
@Override
protected VerificationMode copySelfWithNewVerificationMode(VerificationMode newVerificationMode) {
- return new Timeout(wrappedVerification.getPollingPeriod(), wrappedVerification.getDuration(), newVerificationMode);
+ return new Timeout(wrappedVerification.copyWithVerificationMode(newVerificationMode));
}
-
+
public VerificationMode atMost(int maxNumberOfInvocations) {
new Reporter().atMostAndNeverShouldNotBeUsedWithTimeout();
return null;
@@ -53,5 +57,4 @@ public VerificationMode never() {
new Reporter().atMostAndNeverShouldNotBeUsedWithTimeout();
return null;
}
-
}
\ No newline at end of file
| diff --git a/test/org/mockito/internal/util/TimerTest.java b/test/org/mockito/internal/util/TimerTest.java
index 5e5f0f7841..e1156688c1 100644
--- a/test/org/mockito/internal/util/TimerTest.java
+++ b/test/org/mockito/internal/util/TimerTest.java
@@ -1,6 +1,8 @@
package org.mockito.internal.util;
+import org.junit.Assert;
import org.junit.Test;
+import org.mockito.exceptions.misusing.FriendlyReminderException;
import org.mockitoutil.TestBase;
import static org.hamcrest.CoreMatchers.is;
@@ -15,22 +17,35 @@ public void should_return_true_if_task_is_in_acceptable_time_bounds() {
//when
timer.start();
- boolean stillCounting = timer.isCounting();
//then
- assertThat(stillCounting, is(true));
+ assertThat(timer.isCounting(), is(true));
}
@Test
- public void should_return_false_if_task_is_outside_the_acceptable_time_bounds() {
+ public void should_return_false_when_time_run_out() throws Exception {
//given
- Timer timer = new Timer(-1);
+ Timer timer = new Timer(0);
timer.start();
//when
- boolean stillCounting = timer.isCounting();
+ oneMillisecondPasses();
//then
assertThat(timer.isCounting(), is(false));
}
+
+ @Test
+ public void should_throw_friendly_reminder_exception_when_duration_is_negative() {
+ try {
+ new Timer(-1);
+ Assert.fail("It is forbidden to create timer with negative value of timer's duration.");
+ } catch (FriendlyReminderException e) {
+ Assert.assertTrue(true);
+ }
+ }
+
+ private void oneMillisecondPasses() throws InterruptedException {
+ Thread.sleep(1);
+ }
}
diff --git a/test/org/mockito/verification/NegativeDurationTest.java b/test/org/mockito/verification/NegativeDurationTest.java
new file mode 100644
index 0000000000..fbb2480342
--- /dev/null
+++ b/test/org/mockito/verification/NegativeDurationTest.java
@@ -0,0 +1,29 @@
+package org.mockito.verification;
+
+import org.junit.Assert;
+import org.junit.Test;
+import org.mockito.Mockito;
+import org.mockito.exceptions.misusing.FriendlyReminderException;
+
+public class NegativeDurationTest {
+
+ @Test
+ public void should_throw_exception_when_duration_is_negative_for_timeout_method() {
+ try {
+ Mockito.timeout(-1);
+ Assert.fail("It is forbidden to invoke Mockito.timeout() with negative value.");
+ } catch (FriendlyReminderException e) {
+ Assert.assertTrue(true);
+ }
+ }
+
+ @Test
+ public void should_throw_exception_when_duration_is_negative_for_after_method() {
+ try {
+ Mockito.after(-1);
+ Assert.fail("It is forbidden to invoke Mockito.after() with negative value.");
+ } catch (FriendlyReminderException e) {
+ Assert.assertTrue(true);
+ }
+ }
+}
diff --git a/test/org/mockito/verification/TimeoutTest.java b/test/org/mockito/verification/TimeoutTest.java
index ecd1b63ad8..1272ac0e99 100644
--- a/test/org/mockito/verification/TimeoutTest.java
+++ b/test/org/mockito/verification/TimeoutTest.java
@@ -9,9 +9,6 @@
import org.mockito.Mock;
import org.mockito.exceptions.base.MockitoAssertionError;
import org.mockito.internal.util.Timer;
-import org.mockito.internal.verification.AtLeast;
-import org.mockito.internal.verification.Only;
-import org.mockito.internal.verification.Times;
import org.mockito.internal.verification.VerificationDataImpl;
import org.mockitoutil.TestBase;
@@ -27,7 +24,7 @@ public class TimeoutTest extends TestBase {
@Test
public void should_pass_when_verification_passes() {
- Timeout t = new Timeout(1, 3, mode, timer);
+ Timeout t = new Timeout(1, mode, timer);
when(timer.isCounting()).thenReturn(true);
doNothing().when(mode).verify(data);
@@ -41,7 +38,7 @@ public void should_pass_when_verification_passes() {
@Test
public void should_fail_because_verification_fails() {
- Timeout t = new Timeout(1, 2, mode, timer);
+ Timeout t = new Timeout(1, mode, timer);
when(timer.isCounting()).thenReturn(true, true, true, false);
doThrow(error).
@@ -59,7 +56,7 @@ public void should_fail_because_verification_fails() {
@Test
public void should_pass_even_if_first_verification_fails() {
- Timeout t = new Timeout(1, 5, mode, timer);
+ Timeout t = new Timeout(1, mode, timer);
when(timer.isCounting()).thenReturn(true, true, true, false);
doThrow(error).
@@ -73,7 +70,7 @@ public void should_pass_even_if_first_verification_fails() {
@Test
public void should_try_to_verify_correct_number_of_times() {
- Timeout t = new Timeout(10, 50, mode, timer);
+ Timeout t = new Timeout(10, mode, timer);
doThrow(error).when(mode).verify(data);
when(timer.isCounting()).thenReturn(true, true, true, true, true, false);
@@ -85,21 +82,5 @@ public void should_try_to_verify_correct_number_of_times() {
verify(mode, times(5)).verify(data);
}
-
- @Test
- public void should_create_correctly_configured_timeout() {
- Timeout t = new Timeout(25, 50, mode, timer);
-
- assertTimeoutCorrectlyConfigured(t.atLeastOnce(), Timeout.class, 50, 25, AtLeast.class);
- assertTimeoutCorrectlyConfigured(t.atLeast(5), Timeout.class, 50, 25, AtLeast.class);
- assertTimeoutCorrectlyConfigured(t.times(5), Timeout.class, 50, 25, Times.class);
- assertTimeoutCorrectlyConfigured(t.only(), Timeout.class, 50, 25, Only.class);
- }
-
- private void assertTimeoutCorrectlyConfigured(VerificationMode t, Class<?> expectedType, long expectedTimeout, long expectedPollingPeriod, Class<?> expectedDelegateType) {
- assertEquals(expectedType, t.getClass());
- assertEquals(expectedTimeout, ((Timeout) t).wrappedVerification.getDuration());
- assertEquals(expectedPollingPeriod, ((Timeout) t).wrappedVerification.getPollingPeriod());
- assertEquals(expectedDelegateType, ((Timeout) t).wrappedVerification.getDelegate().getClass());
- }
+
}
\ No newline at end of file
| train | train | 2015-04-19T20:47:19 | "2015-04-13T14:33:49Z" | nathanmbrown | train |
mockito/mockito/188_211 | mockito/mockito | mockito/mockito/188 | mockito/mockito/211 | [
"keyword_issue_to_pr",
"timestamp(timedelta=0.0, similarity=1.0)",
"keyword_pr_to_issue"
] | 0cd01b9d9719ef952035a426eef8272561f35d54 | 30e16ddddae1710ad096356f5a421fe22596c4de | [
"Hi sorry for the late reply.\nI reproduced the issue, not sure when I will be able to fix though.\n",
"fixed by #211 \n"
] | [] | "2015-05-20T19:14:50Z" | [
"bug"
] | ArgumentCaptor no longer working for varargs | I ran into the issue described here: http://stackoverflow.com/questions/27303562/why-does-upgrading-mockito-from-1-9-5-to-1-10-8-break-this-captor
| [
"src/org/mockito/internal/invocation/CapturesArgumensFromInvocation.java",
"src/org/mockito/internal/invocation/InvocationMarker.java",
"src/org/mockito/internal/invocation/InvocationMatcher.java"
] | [
"src/org/mockito/internal/invocation/CapturesArgumentsFromInvocation.java",
"src/org/mockito/internal/invocation/InvocationMarker.java",
"src/org/mockito/internal/invocation/InvocationMatcher.java"
] | [
"test/org/mockito/internal/invocation/InvocationMarkerTest.java",
"test/org/mockito/internal/verification/checkers/AtLeastXNumberOfInvocationsCheckerTest.java",
"test/org/mockitousage/matchers/CapturingArgumentsTest.java"
] | diff --git a/src/org/mockito/internal/invocation/CapturesArgumensFromInvocation.java b/src/org/mockito/internal/invocation/CapturesArgumentsFromInvocation.java
similarity index 83%
rename from src/org/mockito/internal/invocation/CapturesArgumensFromInvocation.java
rename to src/org/mockito/internal/invocation/CapturesArgumentsFromInvocation.java
index cc58b802db..ef7bde459f 100644
--- a/src/org/mockito/internal/invocation/CapturesArgumensFromInvocation.java
+++ b/src/org/mockito/internal/invocation/CapturesArgumentsFromInvocation.java
@@ -7,7 +7,7 @@
import org.mockito.invocation.Invocation;
-public interface CapturesArgumensFromInvocation {
+public interface CapturesArgumentsFromInvocation {
void captureArgumentsFrom(Invocation i);
diff --git a/src/org/mockito/internal/invocation/InvocationMarker.java b/src/org/mockito/internal/invocation/InvocationMarker.java
index 304fdb2ec5..d44cf9f0cd 100644
--- a/src/org/mockito/internal/invocation/InvocationMarker.java
+++ b/src/org/mockito/internal/invocation/InvocationMarker.java
@@ -11,18 +11,18 @@
public class InvocationMarker {
- public void markVerified(List<Invocation> invocations, CapturesArgumensFromInvocation wanted) {
+ public void markVerified(List<Invocation> invocations, CapturesArgumentsFromInvocation wanted) {
for (Invocation invocation : invocations) {
markVerified(invocation, wanted);
}
}
- public void markVerified(Invocation invocation, CapturesArgumensFromInvocation wanted) {
- invocation.markVerified();
- wanted.captureArgumentsFrom(invocation);
- }
+ public void markVerified(Invocation invocation, CapturesArgumentsFromInvocation wanted) {
+ invocation.markVerified();
+ wanted.captureArgumentsFrom(invocation);
+ }
- public void markVerifiedInOrder(List<Invocation> chunk, CapturesArgumensFromInvocation wanted, InOrderContext context) {
+ public void markVerifiedInOrder(List<Invocation> chunk, CapturesArgumentsFromInvocation wanted, InOrderContext context) {
markVerified(chunk, wanted);
for (Invocation i : chunk) {
diff --git a/src/org/mockito/internal/invocation/InvocationMatcher.java b/src/org/mockito/internal/invocation/InvocationMatcher.java
index f1b7b9421f..0e562a0129 100644
--- a/src/org/mockito/internal/invocation/InvocationMatcher.java
+++ b/src/org/mockito/internal/invocation/InvocationMatcher.java
@@ -8,20 +8,18 @@
import java.io.Serializable;
import java.lang.reflect.Array;
import java.lang.reflect.Method;
-import java.util.Collections;
-import java.util.LinkedList;
-import java.util.List;
+import java.util.*;
+
import org.hamcrest.Matcher;
import org.mockito.internal.matchers.CapturesArguments;
import org.mockito.internal.matchers.MatcherDecorator;
-import org.mockito.internal.matchers.VarargMatcher;
import org.mockito.internal.reporting.PrintSettings;
import org.mockito.invocation.DescribedInvocation;
import org.mockito.invocation.Invocation;
import org.mockito.invocation.Location;
@SuppressWarnings("unchecked")
-public class InvocationMatcher implements DescribedInvocation, CapturesArgumensFromInvocation, Serializable {
+public class InvocationMatcher implements DescribedInvocation, CapturesArgumentsFromInvocation, Serializable {
private static final long serialVersionUID = -3047126096857467610L;
private final Invocation invocation;
@@ -99,16 +97,16 @@ public boolean hasSameMethod(Invocation candidate) {
Method m2 = candidate.getMethod();
if (m1.getName() != null && m1.getName().equals(m2.getName())) {
- /* Avoid unnecessary cloning */
- Class[] params1 = m1.getParameterTypes();
- Class[] params2 = m2.getParameterTypes();
- if (params1.length == params2.length) {
- for (int i = 0; i < params1.length; i++) {
- if (params1[i] != params2[i])
- return false;
- }
- return true;
- }
+ /* Avoid unnecessary cloning */
+ Class[] params1 = m1.getParameterTypes();
+ Class[] params2 = m2.getParameterTypes();
+ if (params1.length == params2.length) {
+ for (int i = 0; i < params1.length; i++) {
+ if (params1[i] != params2[i])
+ return false;
+ }
+ return true;
+ }
}
return false;
}
@@ -118,46 +116,55 @@ public Location getLocation() {
}
public void captureArgumentsFrom(Invocation invocation) {
- for (int position = 0; position < matchers.size(); position++) {
+ captureArguments(invocation);
+ if (invocation.getMethod().isVarArgs()) {
+ captureVarargsPart(invocation);
+ }
+ }
+
+ private void captureArguments(Invocation invocation) {
+ for (int position = 0; position < regularArgumentsSize(invocation); position++) {
Matcher m = matchers.get(position);
- if (m instanceof CapturesArguments && invocation.getRawArguments().length > position) {
- //TODO SF - this whole lot can be moved captureFrom implementation
- if(isVariableArgument(invocation, position) && isVarargMatcher(m)) {
- Object array = invocation.getRawArguments()[position];
- for (int i = 0; i < Array.getLength(array); i++) {
- ((CapturesArguments) m).captureFrom(Array.get(array, i));
- }
- //since we've captured all varargs already, it does not make sense to process other matchers.
- return;
- } else {
- ((CapturesArguments) m).captureFrom(invocation.getRawArguments()[position]);
- }
+ if (m instanceof CapturesArguments) {
+ ((CapturesArguments) m).captureFrom(invocation.getArgumentAt(position, Object.class));
}
}
}
- private boolean isVarargMatcher(Matcher matcher) {
- Matcher actualMatcher = matcher;
- if (actualMatcher instanceof MatcherDecorator) {
- actualMatcher = ((MatcherDecorator) actualMatcher).getActualMatcher();
+ private void captureVarargsPart(Invocation invocation) {
+ int indexOfVararg = invocation.getRawArguments().length - 1;
+ for (Matcher m : uniqueMatcherSet(indexOfVararg)) {
+ if (m instanceof CapturesArguments) {
+ Object rawArgument = invocation.getRawArguments()[indexOfVararg];
+ for (int i = 0; i < Array.getLength(rawArgument); i++) {
+ ((CapturesArguments) m).captureFrom(Array.get(rawArgument, i));
+ }
+ }
}
- return actualMatcher instanceof VarargMatcher;
}
- private boolean isVariableArgument(Invocation invocation, int position) {
- return invocation.getRawArguments().length - 1 == position
- && invocation.getRawArguments()[position] != null
- && invocation.getRawArguments()[position].getClass().isArray()
- && invocation.getMethod().isVarArgs();
+ private int regularArgumentsSize(Invocation invocation) {
+ return invocation.getMethod().isVarArgs() ? invocation.getRawArguments().length - 1 : matchers.size();
+ }
+
+ private Set<Matcher> uniqueMatcherSet(int indexOfVararg) {
+ HashSet<Matcher> set = new HashSet<Matcher>();
+ for (int position = indexOfVararg; position < matchers.size(); position++) {
+ Matcher matcher = matchers.get(position);
+ if(matcher instanceof MatcherDecorator) {
+ set.add(((MatcherDecorator) matcher).getActualMatcher());
+ } else {
+ set.add(matcher);
+ }
+ }
+ return set;
}
public static List<InvocationMatcher> createFrom(List<Invocation> invocations) {
LinkedList<InvocationMatcher> out = new LinkedList<InvocationMatcher>();
-
for (Invocation i : invocations) {
out.add(new InvocationMatcher(i));
}
-
return out;
}
}
| diff --git a/test/org/mockito/internal/invocation/InvocationMarkerTest.java b/test/org/mockito/internal/invocation/InvocationMarkerTest.java
index 085b9a808b..d85320c485 100644
--- a/test/org/mockito/internal/invocation/InvocationMarkerTest.java
+++ b/test/org/mockito/internal/invocation/InvocationMarkerTest.java
@@ -35,7 +35,7 @@ public void shouldCaptureArguments() {
InvocationMarker marker = new InvocationMarker();
Invocation i = new InvocationBuilder().toInvocation();
final ObjectBox box = new ObjectBox();
- CapturesArgumensFromInvocation c = new CapturesArgumensFromInvocation() {
+ CapturesArgumentsFromInvocation c = new CapturesArgumentsFromInvocation() {
public void captureArgumentsFrom(Invocation i) {
box.put(i);
}};
diff --git a/test/org/mockito/internal/verification/checkers/AtLeastXNumberOfInvocationsCheckerTest.java b/test/org/mockito/internal/verification/checkers/AtLeastXNumberOfInvocationsCheckerTest.java
index f067708f93..9dfb7ca1c7 100644
--- a/test/org/mockito/internal/verification/checkers/AtLeastXNumberOfInvocationsCheckerTest.java
+++ b/test/org/mockito/internal/verification/checkers/AtLeastXNumberOfInvocationsCheckerTest.java
@@ -28,6 +28,6 @@ public void shouldMarkActualInvocationsAsVerified() {
c.check(asList(invocation, invocationTwo), new InvocationMatcher(invocation), 1);
//then
- Mockito.verify(c.invocationMarker).markVerified(eq(asList(invocation)), any(CapturesArgumensFromInvocation.class));
+ Mockito.verify(c.invocationMarker).markVerified(eq(asList(invocation)), any(CapturesArgumentsFromInvocation.class));
}
}
diff --git a/test/org/mockitousage/matchers/CapturingArgumentsTest.java b/test/org/mockitousage/matchers/CapturingArgumentsTest.java
index d833e681e2..553e913dd7 100644
--- a/test/org/mockitousage/matchers/CapturingArgumentsTest.java
+++ b/test/org/mockitousage/matchers/CapturingArgumentsTest.java
@@ -5,10 +5,10 @@
package org.mockitousage.matchers;
+import org.junit.Assert;
import org.fest.assertions.Assertions;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
-import org.mockito.Mock;
import org.mockito.exceptions.base.MockitoException;
import org.mockito.exceptions.verification.WantedButNotInvoked;
import org.mockitousage.IMethods;
@@ -23,8 +23,6 @@
public class CapturingArgumentsTest extends TestBase {
- @Mock IMethods mock;
-
class Person {
private final Integer age;
@@ -37,12 +35,12 @@ public int getAge() {
return age;
}
}
-
- class Emailer {
-
+
+ class BulkEmailService {
+
private EmailService service;
-
- public Emailer(EmailService service) {
+
+ public BulkEmailService(EmailService service) {
this.service = service;
}
@@ -53,50 +51,53 @@ public void email(Integer ... personId) {
}
}
}
-
+
interface EmailService {
boolean sendEmailTo(Person person);
}
EmailService emailService = mock(EmailService.class);
- Emailer emailer = new Emailer(emailService);
+ BulkEmailService bulkEmailService = new BulkEmailService(emailService);
+ IMethods mock = mock(IMethods.class);
@SuppressWarnings("deprecation")
@Test
public void should_allow_assertions_on_captured_argument() {
+ //given
+ ArgumentCaptor<Person> argument = new ArgumentCaptor<Person>();
+
//when
- emailer.email(12);
-
+ bulkEmailService.email(12);
+
//then
- ArgumentCaptor<Person> argument = new ArgumentCaptor<Person>();
verify(emailService).sendEmailTo(argument.capture());
-
assertEquals(12, argument.getValue().getAge());
}
@Test
public void should_allow_assertions_on_all_captured_arguments() {
+ //given
+ ArgumentCaptor<Person> argument = ArgumentCaptor.forClass(Person.class);
+
//when
- emailer.email(11, 12);
-
+ bulkEmailService.email(11, 12);
+
//then
- ArgumentCaptor<Person> argument = ArgumentCaptor.forClass(Person.class);
- verify(emailService, atLeastOnce()).sendEmailTo(argument.capture());
- List<Person> allValues = argument.getAllValues();
-
- assertEquals(11, allValues.get(0).getAge());
- assertEquals(12, allValues.get(1).getAge());
+ verify(emailService, times(2)).sendEmailTo(argument.capture());
+ assertEquals(11, argument.getAllValues().get(0).getAge());
+ assertEquals(12, argument.getAllValues().get(1).getAge());
}
@Test
public void should_allow_assertions_on_last_argument() {
+ //given
+ ArgumentCaptor<Person> argument = ArgumentCaptor.forClass(Person.class);
+
//when
- emailer.email(11, 12, 13);
-
+ bulkEmailService.email(11, 12, 13);
+
//then
- ArgumentCaptor<Person> argument = ArgumentCaptor.forClass(Person.class);
- verify(emailService, atLeastOnce()).sendEmailTo(argument.capture());
-
+ verify(emailService, times(3)).sendEmailTo(argument.capture());
assertEquals(13, argument.getValue().getAge());
}
@@ -117,11 +118,13 @@ public void should_print_captor_matcher() {
@Test
public void should_allow_assertions_on_captured_null() {
+ //given
+ ArgumentCaptor<Person> argument = ArgumentCaptor.forClass(Person.class);
+
//when
emailService.sendEmailTo(null);
-
+
//then
- ArgumentCaptor<Person> argument = ArgumentCaptor.forClass(Person.class);
verify(emailService).sendEmailTo(argument.capture());
assertEquals(null, argument.getValue());
}
@@ -130,12 +133,14 @@ public void should_allow_assertions_on_captured_null() {
public void should_allow_construction_of_captor_for_parameterized_type_in_a_convenient_way() {
//the test passes if this expression compiles
ArgumentCaptor<List<Person>> argument = ArgumentCaptor.forClass(List.class);
+ assertNotNull(argument);
}
@Test
public void should_allow_construction_of_captor_for_a_more_specific_type() {
//the test passes if this expression compiles
ArgumentCaptor<List> argument = ArgumentCaptor.forClass(ArrayList.class);
+ assertNotNull(argument);
}
@Test
@@ -171,20 +176,22 @@ public void should_say_something_smart_when_misused() {
try {
argument.getValue();
fail();
- } catch (MockitoException e) {}
+ } catch (MockitoException e) {
+ Assert.assertTrue(true);
+ }
}
@Test
public void should_capture_when_full_arg_list_matches() throws Exception {
//given
+ ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
+
+ //when
mock.simpleMethod("foo", 1);
mock.simpleMethod("bar", 2);
-
- //when
- ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
- verify(mock).simpleMethod(captor.capture(), eq(1));
-
+
//then
+ verify(mock).simpleMethod(captor.capture(), eq(1));
assertEquals(1, captor.getAllValues().size());
assertEquals("foo", captor.getValue());
}
@@ -192,7 +199,6 @@ public void should_capture_when_full_arg_list_matches() throws Exception {
@Test
public void should_capture_int_by_creating_captor_with_primitive_wrapper() {
//given
- IMethods mock = mock(IMethods.class);
ArgumentCaptor<Integer> argument = ArgumentCaptor.forClass(Integer.class);
//when
@@ -206,7 +212,6 @@ public void should_capture_int_by_creating_captor_with_primitive_wrapper() {
@Test
public void should_capture_int_by_creating_captor_with_primitive() throws Exception {
//given
- IMethods mock = mock(IMethods.class);
ArgumentCaptor<Integer> argument = ArgumentCaptor.forClass(int.class);
//when
@@ -220,7 +225,6 @@ public void should_capture_int_by_creating_captor_with_primitive() throws Except
@Test
public void should_capture_byte_vararg_by_creating_captor_with_primitive() throws Exception {
// given
- IMethods mock = mock(IMethods.class);
ArgumentCaptor<Byte> argumentCaptor = ArgumentCaptor.forClass(byte.class);
// when
@@ -235,7 +239,6 @@ public void should_capture_byte_vararg_by_creating_captor_with_primitive() throw
@Test
public void should_capture_byte_vararg_by_creating_captor_with_primitive_wrapper() throws Exception {
// given
- IMethods mock = mock(IMethods.class);
ArgumentCaptor<Byte> argumentCaptor = ArgumentCaptor.forClass(Byte.class);
// when
@@ -250,7 +253,6 @@ public void should_capture_byte_vararg_by_creating_captor_with_primitive_wrapper
@Test
public void should_capture_vararg() throws Exception {
// given
- IMethods mock = mock(IMethods.class);
ArgumentCaptor<String> argumentCaptor = ArgumentCaptor.forClass(String.class);
// when
@@ -264,7 +266,6 @@ public void should_capture_vararg() throws Exception {
@Test
public void should_capture_all_vararg() throws Exception {
// given
- IMethods mock = mock(IMethods.class);
ArgumentCaptor<String> argumentCaptor = ArgumentCaptor.forClass(String.class);
// when
@@ -274,14 +275,12 @@ public void should_capture_all_vararg() throws Exception {
// then
verify(mock, times(2)).mixedVarargs(any(), argumentCaptor.capture());
- List<String> allVarargsValues = argumentCaptor.getAllValues();
- Assertions.assertThat(allVarargsValues).containsExactly("a", "b", "c", "again ?!");
+ Assertions.assertThat(argumentCaptor.getAllValues()).containsExactly("a", "b", "c", "again ?!");
}
@Test
public void should_capture_one_arg_even_when_using_vararg_captor_on_nonvararg_method() throws Exception {
// given
- IMethods mock = mock(IMethods.class);
ArgumentCaptor<String> argumentCaptor = ArgumentCaptor.forClass(String.class);
// when
@@ -293,9 +292,8 @@ public void should_capture_one_arg_even_when_using_vararg_captor_on_nonvararg_me
}
@Test
- public void captures_correclty_when_captor_used_multiple_times() throws Exception {
+ public void captures_correctly_when_captor_used_multiple_times() throws Exception {
// given
- IMethods mock = mock(IMethods.class);
ArgumentCaptor<String> argumentCaptor = ArgumentCaptor.forClass(String.class);
// when
@@ -306,4 +304,17 @@ public void captures_correclty_when_captor_used_multiple_times() throws Exceptio
verify(mock).mixedVarargs(any(), argumentCaptor.capture(), argumentCaptor.capture(), argumentCaptor.capture());
Assertions.assertThat(argumentCaptor.getAllValues()).containsExactly("a", "b", "c");
}
+
+ @Test
+ public void captures_correctly_when_captor_used_on_pure_vararg_method() throws Exception {
+ // given
+ ArgumentCaptor<String> argumentCaptor = ArgumentCaptor.forClass(String.class);
+
+ // when
+ mock.varargs(42, "capturedValue");
+
+ // then
+ verify(mock).varargs(eq(42), argumentCaptor.capture());
+ Assertions.assertThat(argumentCaptor.getValue()).contains("capturedValue");
+ }
}
\ No newline at end of file
| train | train | 2015-06-04T08:58:29 | "2015-04-01T00:16:10Z" | vadims | train |
mockito/mockito/205_215 | mockito/mockito | mockito/mockito/205 | mockito/mockito/215 | [
"timestamp(timedelta=0.0, similarity=0.87539028548778)"
] | 03028f0095d527ff9bd84bc929fc4931f17abf13 | 32ceae5e361a96641785a7c75d87e49c50505663 | [
"@SimenB Maybe txtNextStep TextView Class Mocking the aneunge not work properly?\nA bug or would not even be on @InjectMocks features?\n",
"I have answered a similar question on Stackoverflow and you can find my investigations at http://stackoverflow.com/a/29954211/2761676\n",
"@JeremybellEU Yeah, that seems to be the same thing.\nWhile it explains _why_ it happens, I still consider it to be a bug...\n",
"Not a bug, it is just something that was left off.\n\nThanks @JeremybellEU, I'll look into your PR. Note the merge is gonna happen in 2.x line (which is beta and subject to important changes, both internally and API wise).\n",
"After I commented I realised I probably knew how to fix it, so I hope the PR is useful =]. Looking forward to Mockito 2.0.\n"
] | [] | "2015-06-02T22:55:10Z" | [] | InjectMocks injects mock into wrong field | Using `1.10.19`.
When using `@InjectMocks` on some Android `TextView`s, the mock is injected into the wrong field.
We have two fields, `txtGateView` & `txtNextStep` in a class, and our test mocks out `txtNextStep`, then tried to inject. This field is injected wrong, see screenshot.
![image](https://cloud.githubusercontent.com/assets/1404810/7410003/4f200580-ef2b-11e4-9c39-7a699dc4fefa.png)
From our quick testing, the name `txtNextView` doesn't matter, that can be changed. But both `txtGateView` and `txtGateLabel` messed things up. If we mock out both fields, it works correctly.
Testproject: https://github.com/SimenB/emptyandroid
I don't know if it's because it's Android, but it was easiest for me to create a minimal test from existing code.
| [
"src/org/mockito/internal/configuration/injection/PropertyAndSetterInjection.java",
"src/org/mockito/internal/configuration/injection/filter/FinalMockCandidateFilter.java",
"src/org/mockito/internal/configuration/injection/filter/MockCandidateFilter.java",
"src/org/mockito/internal/configuration/injection/filter/NameBasedCandidateFilter.java",
"src/org/mockito/internal/configuration/injection/filter/TypeBasedCandidateFilter.java"
] | [
"src/org/mockito/internal/configuration/injection/PropertyAndSetterInjection.java",
"src/org/mockito/internal/configuration/injection/filter/FinalMockCandidateFilter.java",
"src/org/mockito/internal/configuration/injection/filter/MockCandidateFilter.java",
"src/org/mockito/internal/configuration/injection/filter/NameBasedCandidateFilter.java",
"src/org/mockito/internal/configuration/injection/filter/TypeBasedCandidateFilter.java"
] | [
"test/org/mockitousage/annotation/MockInjectionUsingSetterOrPropertyTest.java"
] | diff --git a/src/org/mockito/internal/configuration/injection/PropertyAndSetterInjection.java b/src/org/mockito/internal/configuration/injection/PropertyAndSetterInjection.java
index 67126afd95..c17f961c5a 100644
--- a/src/org/mockito/internal/configuration/injection/PropertyAndSetterInjection.java
+++ b/src/org/mockito/internal/configuration/injection/PropertyAndSetterInjection.java
@@ -111,7 +111,7 @@ private boolean injectMockCandidates(Class<?> awaitingInjectionClazz, Set<Object
private boolean injectMockCandidatesOnFields(Set<Object> mocks, Object instance, boolean injectionOccurred, List<Field> orderedInstanceFields) {
for (Iterator<Field> it = orderedInstanceFields.iterator(); it.hasNext(); ) {
Field field = it.next();
- Object injected = mockCandidateFilter.filterCandidate(mocks, field, instance).thenInject();
+ Object injected = mockCandidateFilter.filterCandidate(mocks, field, orderedInstanceFields, instance).thenInject();
if (injected != null) {
injectionOccurred |= true;
mocks.remove(injected);
diff --git a/src/org/mockito/internal/configuration/injection/filter/FinalMockCandidateFilter.java b/src/org/mockito/internal/configuration/injection/filter/FinalMockCandidateFilter.java
index 7bd70735f7..aebf6f71e4 100644
--- a/src/org/mockito/internal/configuration/injection/filter/FinalMockCandidateFilter.java
+++ b/src/org/mockito/internal/configuration/injection/filter/FinalMockCandidateFilter.java
@@ -10,6 +10,7 @@
import java.lang.reflect.Field;
import java.util.Collection;
+import java.util.List;
/**
* This node returns an actual injecter which will be either :
@@ -20,7 +21,7 @@
* </ul>
*/
public class FinalMockCandidateFilter implements MockCandidateFilter {
- public OngoingInjecter filterCandidate(final Collection<Object> mocks, final Field field, final Object fieldInstance) {
+ public OngoingInjecter filterCandidate(final Collection<Object> mocks, final Field field, List<Field> fields, final Object fieldInstance) {
if(mocks.size() == 1) {
final Object matchingMock = mocks.iterator().next();
diff --git a/src/org/mockito/internal/configuration/injection/filter/MockCandidateFilter.java b/src/org/mockito/internal/configuration/injection/filter/MockCandidateFilter.java
index 7a2c08781e..81a168b491 100644
--- a/src/org/mockito/internal/configuration/injection/filter/MockCandidateFilter.java
+++ b/src/org/mockito/internal/configuration/injection/filter/MockCandidateFilter.java
@@ -6,13 +6,14 @@
import java.lang.reflect.Field;
import java.util.Collection;
+import java.util.List;
public interface MockCandidateFilter {
OngoingInjecter filterCandidate(
Collection<Object> mocks,
Field fieldToBeInjected,
- Object fieldInstance
+ List<Field> fields, Object instance
);
}
diff --git a/src/org/mockito/internal/configuration/injection/filter/NameBasedCandidateFilter.java b/src/org/mockito/internal/configuration/injection/filter/NameBasedCandidateFilter.java
index 7023e66ba2..abc5d67b45 100644
--- a/src/org/mockito/internal/configuration/injection/filter/NameBasedCandidateFilter.java
+++ b/src/org/mockito/internal/configuration/injection/filter/NameBasedCandidateFilter.java
@@ -12,23 +12,50 @@
import java.util.List;
public class NameBasedCandidateFilter implements MockCandidateFilter {
- private final MockCandidateFilter next;
- private final MockUtil mockUtil = new MockUtil();
+ private final MockCandidateFilter next;
+ private final MockUtil mockUtil = new MockUtil();
- public NameBasedCandidateFilter(MockCandidateFilter next) {
- this.next = next;
- }
+ public NameBasedCandidateFilter(MockCandidateFilter next) {
+ this.next = next;
+ }
- public OngoingInjecter filterCandidate(Collection<Object> mocks, Field field, Object fieldInstance) {
- List<Object> mockNameMatches = new ArrayList<Object>();
- if(mocks.size() > 1) {
- for (Object mock : mocks) {
- if (field.getName().equals(mockUtil.getMockName(mock).toString())) {
- mockNameMatches.add(mock);
- }
- }
- return next.filterCandidate(mockNameMatches, field, fieldInstance);
- }
- return next.filterCandidate(mocks, field, fieldInstance);
- }
+ public OngoingInjecter filterCandidate(Collection<Object> mocks,
+ Field field, List<Field> fields, Object fieldInstance) {
+ List<Object> mockNameMatches = new ArrayList<Object>();
+ if (mocks.size() > 1) {
+ for (Object mock : mocks) {
+ if (field.getName().equals(mockUtil.getMockName(mock).toString())) {
+ mockNameMatches.add(mock);
+ }
+ }
+ return next.filterCandidate(mockNameMatches, field, fields,
+ fieldInstance);
+ /*
+ * In this case we have to check whether we have conflicting naming
+ * fields. E.g. 2 fields of the same type, but we have to make sure
+ * we match on the correct name.
+ *
+ * Therefore we have to go through all other fields and make sure
+ * whenever we find a field that does match its name with the mock
+ * name, we should take that field instead.
+ */
+ } else if (mocks.size() == 1) {
+ String mockName = mockUtil.getMockName(mocks.iterator().next())
+ .toString();
+
+ for (Field otherField : fields) {
+ if (!otherField.equals(field)
+ && otherField.getType().equals(field.getType())
+ && otherField.getName().equals(mockName)) {
+
+ return new OngoingInjecter() {
+ public Object thenInject() {
+ return null;
+ }
+ };
+ }
+ }
+ }
+ return next.filterCandidate(mocks, field, fields, fieldInstance);
+ }
}
diff --git a/src/org/mockito/internal/configuration/injection/filter/TypeBasedCandidateFilter.java b/src/org/mockito/internal/configuration/injection/filter/TypeBasedCandidateFilter.java
index dd79991a65..ce7a349fa7 100644
--- a/src/org/mockito/internal/configuration/injection/filter/TypeBasedCandidateFilter.java
+++ b/src/org/mockito/internal/configuration/injection/filter/TypeBasedCandidateFilter.java
@@ -17,7 +17,7 @@ public TypeBasedCandidateFilter(MockCandidateFilter next) {
this.next = next;
}
- public OngoingInjecter filterCandidate(Collection<Object> mocks, Field field, Object fieldInstance) {
+ public OngoingInjecter filterCandidate(Collection<Object> mocks, Field field, List<Field> fields, Object fieldInstance) {
List<Object> mockTypeMatches = new ArrayList<Object>();
for (Object mock : mocks) {
if (field.getType().isAssignableFrom(mock.getClass())) {
@@ -25,6 +25,6 @@ public OngoingInjecter filterCandidate(Collection<Object> mocks, Field field, Ob
}
}
- return next.filterCandidate(mockTypeMatches, field, fieldInstance);
+ return next.filterCandidate(mockTypeMatches, field, fields, fieldInstance);
}
}
| diff --git a/test/org/mockitousage/annotation/MockInjectionUsingSetterOrPropertyTest.java b/test/org/mockitousage/annotation/MockInjectionUsingSetterOrPropertyTest.java
index bd49f3adee..c6eb915851 100644
--- a/test/org/mockitousage/annotation/MockInjectionUsingSetterOrPropertyTest.java
+++ b/test/org/mockitousage/annotation/MockInjectionUsingSetterOrPropertyTest.java
@@ -4,6 +4,9 @@
*/
package org.mockitousage.annotation;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+
import org.fest.assertions.Assertions;
import org.junit.Before;
import org.junit.Test;
@@ -28,6 +31,7 @@ public class MockInjectionUsingSetterOrPropertyTest extends TestBase {
@InjectMocks private BaseUnderTesting baseUnderTest = new BaseUnderTesting();
@InjectMocks private SubUnderTesting subUnderTest = new SubUnderTesting();
@InjectMocks private OtherBaseUnderTesting otherBaseUnderTest = new OtherBaseUnderTesting();
+ @InjectMocks private OtherSuperUnderTesting otherSuperUnderTesting = new OtherSuperUnderTesting();
private BaseUnderTesting baseUnderTestingInstance = new BaseUnderTesting();
@InjectMocks private BaseUnderTesting initializedBase = baseUnderTestingInstance;
@@ -40,6 +44,8 @@ public class MockInjectionUsingSetterOrPropertyTest extends TestBase {
@Mock private List list;
@Mock private Set histogram1;
@Mock private Set histogram2;
+ @Mock private A candidate2;
+
@Spy private TreeSet searchTree = new TreeSet();
private MockUtil mockUtil = new MockUtil();
@@ -103,6 +109,13 @@ public void shouldInjectSpies() {
assertSame(searchTree, otherBaseUnderTest.getSearchTree());
}
+ @Test
+ public void shouldInsertFieldWithCorrectNameWhenMultipleTypesAvailable() {
+ MockitoAnnotations.initMocks(this);
+ assertNull(otherSuperUnderTesting.candidate1);
+ assertNotNull(otherSuperUnderTesting.candidate2);
+ }
+
@Test
public void shouldInstantiateInjectMockFieldIfPossible() throws Exception {
assertNotNull(notInitializedBase);
@@ -168,4 +181,15 @@ public Set getHistogram2() {
return histogram2;
}
}
+
+ static class OtherSuperUnderTesting {
+ private A candidate1;
+
+ private A candidate2;
+ }
+
+ interface A {
+ }
+
+
}
| train | train | 2015-06-02T21:54:46 | "2015-04-30T09:25:09Z" | SimenB | train |
mockito/mockito/212_221 | mockito/mockito | mockito/mockito/212 | mockito/mockito/221 | [
"keyword_pr_to_issue",
"timestamp(timedelta=2.0, similarity=0.8905683933467733)"
] | 0cd01b9d9719ef952035a426eef8272561f35d54 | 01b0100e3cd3de6baa3359a8175c24b245067393 | [
"OK, are you ready for a PR ?\n",
"@bric3, please see #221\n"
] | [] | "2015-06-04T16:51:45Z" | [
"enhancement",
"BDD"
] | Add BDD version of verifyZeroInteractions() | Right now my tests look like:
``` java
then(file).should().moveTo(directory);
then(log).should().warn("Moved file"));
verifyZeroInteractions(otherFile);
```
Would be great to have BDD replacement for `verifyZeroInteractions()`. Then the test would be even nicer:
``` java
then(file).should().moveTo(directory);
then(log).should().warn("Moved file"));
then(otherFile).shouldHaveZeroInteractions();
```
| [
"src/org/mockito/BDDMockito.java"
] | [
"src/org/mockito/BDDMockito.java"
] | [
"test/org/mockitousage/customization/BDDMockitoTest.java"
] | diff --git a/src/org/mockito/BDDMockito.java b/src/org/mockito/BDDMockito.java
index 3d008b5516..d0e280c665 100644
--- a/src/org/mockito/BDDMockito.java
+++ b/src/org/mockito/BDDMockito.java
@@ -57,6 +57,7 @@
* person.ride(bike);
*
* then(person).should(times(2)).ride(bike);
+ * then(police).shouldHaveZeroInteractions();
* </code></pre>
*
* One of the purposes of BDDMockito is also to show how to tailor the mocking syntax to a different programming style.
@@ -229,6 +230,12 @@ public static interface Then<T> {
* @since 1.10.5
*/
T should(VerificationMode mode);
+
+ /**
+ * @see #verifyZeroInteractions(Object...)
+ * @since 2.0.0
+ */
+ void shouldHaveZeroInteractions();
}
static class ThenImpl<T> implements Then<T> {
@@ -254,6 +261,14 @@ public T should() {
public T should(VerificationMode mode) {
return verify(mock, mode);
}
+
+ /**
+ * @see #verifyZeroInteractions(Object...)
+ * @since 2.0.0
+ */
+ public void shouldHaveZeroInteractions() {
+ verifyZeroInteractions(mock);
+ }
}
/**
| diff --git a/test/org/mockitousage/customization/BDDMockitoTest.java b/test/org/mockitousage/customization/BDDMockitoTest.java
index 8211338b43..71b50196bc 100644
--- a/test/org/mockitousage/customization/BDDMockitoTest.java
+++ b/test/org/mockitousage/customization/BDDMockitoTest.java
@@ -7,6 +7,7 @@
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.exceptions.misusing.NotAMockException;
+import org.mockito.exceptions.verification.NoInteractionsWanted;
import org.mockito.exceptions.verification.WantedButNotInvoked;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
@@ -222,16 +223,32 @@ public void shouldPassForExpectedBehaviorThatHappened() {
then(mock).should().booleanObjectReturningMethod();
}
+ @Test
+ public void shouldValidateThatMockDidNotHaveAnyInteractions() {
+
+ then(mock).shouldHaveZeroInteractions();
+ }
+
+ @Test(expected = NoInteractionsWanted.class)
+ public void shouldFailWhenMockHadUnwantedInteractions() {
+
+ mock.booleanObjectReturningMethod();
+
+ then(mock).shouldHaveZeroInteractions();
+ }
+
@Test
public void shouldPassFluentBddScenario() {
Bike bike = new Bike();
Person person = mock(Person.class);
+ Police police = mock(Police.class);
person.ride(bike);
person.ride(bike);
then(person).should(times(2)).ride(bike);
+ then(police).shouldHaveZeroInteractions();
}
static class Person {
@@ -242,4 +259,8 @@ void ride(Bike bike) {}
static class Bike {
}
+
+ static class Police {
+
+ }
}
| train | train | 2015-06-04T08:58:29 | "2015-05-22T05:48:18Z" | mkordas | train |
mockito/mockito/203_222 | mockito/mockito | mockito/mockito/203 | mockito/mockito/222 | [
"keyword_pr_to_issue",
"timestamp(timedelta=0.0, similarity=0.9299964359171426)"
] | 1ccd0e7bacfbc56e4e796cbde2ff3a896f71c1ad | 61477c40e15480e5f00f3ea4cbffa23b34d2b1b8 | [
"It seems like a nice idea, let's introduce ordered BDD. I'd favor proposition 2, it reads better imho.\n\nSince we are in a beta phase, we can try and see if the API works with this proposition. Also it should probably be easier to implement.\n",
"Also sorry for this late reply\n",
"@bric3, I've implemented the second proposition. I also like it more and implementation was really easy - please see #222.\n"
] | [] | "2015-06-04T18:03:08Z" | [
"enhancement",
"BDD"
] | Introduce BDD InOrder verification | Follow-up to the [discussion](https://groups.google.com/forum/#!topic/mockito/wr1As1fg_-U).
[BDDMockito](http://site.mockito.org/mockito/docs/current/org/mockito/BDDMockito.html) is great, but right now it doesn't support InOrder verification. Here is my proposition:
##### Initialization and invocations:
``` java
List firstMock = mock(List.class);
List secondMock = mock(List.class);
firstMock.add("was called first");
secondMock.add("was called second");
secondMock.add("was called second");
InOrder inOrder = inOrder(firstMock, secondMock);
```
##### Current non-BDD solution:
``` java
inOrder.verify(firstMock).add("was called first");
inOrder.verify(secondMock).add("was called second");
```
##### Proposition 1:
``` java
inOrder.then(firstMock).should().add("was called first");
inOrder.then(secondMock).should(times(2)).add("was called second");
```
##### Proposition 2:
``` java
then(firstMock).should(inOrder).add("was called first");
then(secondMock).should(inOrder, times(2)).add("was called second");
```
I'm open to other propositions. What do you think?
I can proceed with PR as soon as we will agree on API.
| [
"src/org/mockito/BDDMockito.java"
] | [
"src/org/mockito/BDDMockito.java"
] | [
"test/org/mockitousage/customization/BDDMockitoTest.java"
] | diff --git a/src/org/mockito/BDDMockito.java b/src/org/mockito/BDDMockito.java
index d0e280c665..4ab46397d2 100644
--- a/src/org/mockito/BDDMockito.java
+++ b/src/org/mockito/BDDMockito.java
@@ -59,7 +59,19 @@
* then(person).should(times(2)).ride(bike);
* then(police).shouldHaveZeroInteractions();
* </code></pre>
+ * <p>
+ * It is also possible to do BDD style {@link InOrder} verification:
+ * <pre class="code"><code class="java">
+ * InOrder inOrder = inOrder(person);
+ *
+ * person.drive(car);
+ * person.ride(bike);
+ * person.ride(bike);
*
+ * then(person).should(inOrder).drive(car);
+ * then(person).should(inOrder, times(2)).ride(bike);
+ * </code></pre>
+ * <p>
* One of the purposes of BDDMockito is also to show how to tailor the mocking syntax to a different programming style.
*
* @since 1.8.0
@@ -231,9 +243,21 @@ public static interface Then<T> {
*/
T should(VerificationMode mode);
+ /**
+ * @see InOrder#verify(Object)
+ * @since 2.0
+ */
+ T should(InOrder inOrder);
+
+ /**
+ * @see InOrder#verify(Object, VerificationMode)
+ * @since 2.0
+ */
+ T should(InOrder inOrder, VerificationMode mode);
+
/**
* @see #verifyZeroInteractions(Object...)
- * @since 2.0.0
+ * @since 2.0
*/
void shouldHaveZeroInteractions();
}
@@ -262,9 +286,25 @@ public T should(VerificationMode mode) {
return verify(mock, mode);
}
+ /**
+ * @see InOrder#verify(Object)
+ * @since 2.0
+ */
+ public T should(InOrder inOrder) {
+ return inOrder.verify(mock);
+ }
+
+ /**
+ * @see InOrder#verify(Object, VerificationMode)
+ * @since 2.0
+ */
+ public T should(InOrder inOrder, VerificationMode mode) {
+ return inOrder.verify(mock, mode);
+ }
+
/**
* @see #verifyZeroInteractions(Object...)
- * @since 2.0.0
+ * @since 2.0
*/
public void shouldHaveZeroInteractions() {
verifyZeroInteractions(mock);
| diff --git a/test/org/mockitousage/customization/BDDMockitoTest.java b/test/org/mockitousage/customization/BDDMockitoTest.java
index 71b50196bc..8b9324cfdd 100644
--- a/test/org/mockitousage/customization/BDDMockitoTest.java
+++ b/test/org/mockitousage/customization/BDDMockitoTest.java
@@ -5,9 +5,11 @@
package org.mockitousage.customization;
import org.junit.Test;
+import org.mockito.InOrder;
import org.mockito.Mock;
import org.mockito.exceptions.misusing.NotAMockException;
import org.mockito.exceptions.verification.NoInteractionsWanted;
+import org.mockito.exceptions.verification.VerificationInOrderFailure;
import org.mockito.exceptions.verification.WantedButNotInvoked;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
@@ -237,6 +239,38 @@ public void shouldFailWhenMockHadUnwantedInteractions() {
then(mock).shouldHaveZeroInteractions();
}
+ @Test
+ public void shouldPassForInteractionsThatHappenedInCorrectOrder() {
+
+ InOrder inOrder = inOrder(mock);
+
+ mock.booleanObjectReturningMethod();
+ mock.arrayReturningMethod();
+
+ then(mock).should(inOrder).booleanObjectReturningMethod();
+ then(mock).should(inOrder).arrayReturningMethod();
+ }
+
+ @Test(expected = VerificationInOrderFailure.class)
+ public void shouldFailForInteractionsThatWereInWrongOrder() {
+
+ InOrder inOrder = inOrder(mock);
+
+ mock.arrayReturningMethod();
+ mock.booleanObjectReturningMethod();
+
+ then(mock).should(inOrder).booleanObjectReturningMethod();
+ then(mock).should(inOrder).arrayReturningMethod();
+ }
+
+ @Test(expected = WantedButNotInvoked.class)
+ public void shouldFailWhenCheckingOrderOfInteractionsThatDidNotHappen() {
+
+ InOrder inOrder = inOrder(mock);
+
+ then(mock).should(inOrder).booleanObjectReturningMethod();
+ }
+
@Test
public void shouldPassFluentBddScenario() {
@@ -251,16 +285,55 @@ public void shouldPassFluentBddScenario() {
then(police).shouldHaveZeroInteractions();
}
+ @Test
+ public void shouldPassFluentBddScenarioWithOrderedVerification() {
+
+ Bike bike = new Bike();
+ Car car = new Car();
+ Person person = mock(Person.class);
+ InOrder inOrder = inOrder(person);
+
+ person.drive(car);
+ person.ride(bike);
+ person.ride(bike);
+
+ then(person).should(inOrder).drive(car);
+ then(person).should(inOrder, times(2)).ride(bike);
+ }
+
+ @Test
+ public void shouldPassFluentBddScenarioWithOrderedVerificationForTwoMocks() {
+
+ Car car = new Car();
+ Person person = mock(Person.class);
+ Police police = mock(Police.class);
+ InOrder inOrder = inOrder(person, police);
+
+ person.drive(car);
+ person.drive(car);
+ police.chase(car);
+
+ then(person).should(inOrder, times(2)).drive(car);
+ then(police).should(inOrder).chase(car);
+ }
+
static class Person {
void ride(Bike bike) {}
+
+ void drive(Car car) {}
}
static class Bike {
}
+ static class Car {
+
+ }
+
static class Police {
+ void chase(Car car) {}
}
}
| test | train | 2015-06-04T19:01:12 | "2015-04-25T21:50:45Z" | mkordas | train |
mockito/mockito/228_229 | mockito/mockito | mockito/mockito/228 | mockito/mockito/229 | [
"timestamp(timedelta=1.0, similarity=0.8770086465478265)"
] | 2a686ff33684ba12cd3d82e17bd6882588ae6a7f | b561284b7d52ed187127b89d8715ce173878e859 | [
"Cool thanks :)\n"
] | [] | "2015-06-11T07:29:49Z" | [] | @Captor javadoc contains a wrong call example | In the javadoc of `@Captor`:
```
verify(mock.doStuff(captor.capture()));
```
which is incorrect.
| [
"src/org/mockito/Captor.java"
] | [
"src/org/mockito/Captor.java"
] | [] | diff --git a/src/org/mockito/Captor.java b/src/org/mockito/Captor.java
index 1a081a2513..225bf700f2 100644
--- a/src/org/mockito/Captor.java
+++ b/src/org/mockito/Captor.java
@@ -22,7 +22,7 @@
*
* @Test public void shouldDoSomethingUseful() {
* //...
- * verify(mock.doStuff(captor.capture()));
+ * verify(mock).doStuff(captor.capture());
* assertEquals("foo", captor.getValue());
* }
* }
| null | test | train | 2015-06-06T21:43:00 | "2015-06-11T07:23:56Z" | eugene-ivakhno | train |
mockito/mockito/231_232 | mockito/mockito | mockito/mockito/231 | mockito/mockito/232 | [
"timestamp(timedelta=169247.0, similarity=0.9113863832886153)"
] | 6b5424acebc1bc4ebaca97d6592ade901d1fb838 | 3359a126b5e0a45f084820c615ae007736367121 | [
"Hi @durron597, no actualluy the plan is to not make hamcrest as required dependency at all, just like JUnit is a not a required dependency.\n",
"I understand that's the plan, I'm just saying, as a temporary change, in between now and the time you have hamcrest not be a required dependency at all, advancing the hamcrest version.\n",
"We can do that in 2.0 beta phase, but as development evolves API may break during that phase.\nIn 1.x we didn't upgrade for backward compatibility reasons.\n\nI'll think about it.\n",
"I see no problem bumping to latest hamcrest now. PR is welcome. I hope we\ncan get rid of compile dependency to hamcrest. Thanks!\n\nOn Fri, Jun 12, 2015, 12:01 Brice Dutheil notifications@github.com wrote:\n\n> We can do that in 2.0 beta phase, but as development evolves API may break\n> during that phase.\n> In 1.x we didn't upgrade for backward compatibility reasons.\n> \n> I'll think about it.\n> \n> —\n> Reply to this email directly or view it on GitHub\n> https://github.com/mockito/mockito/issues/231#issuecomment-111589566.\n",
"Thanks! One quick question though... You want a pull request for a one line change to a maven pom? I mean, I'll do it if you really need me to...\n",
"Yes please :)\n\nOn Sat, Jun 13, 2015 at 4:35 PM, durron597 notifications@github.com wrote:\n\n> Thanks! One quick question though... You want a pull request for a one\n> line change to a maven pom? I mean, I'll do it if you really need me to...\n> \n> —\n> Reply to this email directly or view it on GitHub\n> https://github.com/mockito/mockito/issues/231#issuecomment-111760394.\n\n## \n\nSzczepan Faber\nFounder mockito.org; Core dev gradle.org\ntweets as @szczepiq; blogs at blog.mockito.org\n",
"Okay, I suppose you are using Gradle now and not Maven. I made the change in my fork, but I was searching through to make sure that's the only change needed and saw [this file](https://github.com/mockito/mockito/blob/425a6745f48a4ccb158206e23103b885da3f91b3/buildSrc/src/test/groovy/org/mockito/release/comparison/PomComparatorTest.groovy); I'm not sure what it does. Does it need to be changed as well?\n",
"Yes Mockito is built with gradle, but the script has to generate a pom file. This [pom.gradle](https://github.com/mockito/mockito/blob/master/gradle/pom.gradle) takes care of that. The test you are referring to is for the release/publish phase.\n",
"Fixed on master.\n"
] | [] | "2015-06-15T14:13:09Z" | [] | Upgrade to Hamcrest 1.3 in pom | I know this may be a meaningless case because of #154, but if you're going to [continue to release versions of Mockito that include hamcrest as a required dependency in the pom](http://central.maven.org/maven2/org/mockito/mockito-core/2.0.13-beta/mockito-core-2.0.13-beta.pom), could you at least upgrade it to 1.3? JUnit 4.11 has been out, using Hamcrest 1.3 since 2012.
[Related Stack Overflow question](http://stackoverflow.com/questions/18770943/mockito-junit-hamcrest-versioning)
| [
"build.gradle",
"src/org/mockito/internal/matchers/LocalizedMatcher.java"
] | [
"build.gradle",
"src/org/mockito/internal/matchers/LocalizedMatcher.java"
] | [
"test/org/mockito/internal/runners/RunnerFactoryTest.java",
"test/org/mockitousage/basicapi/MocksCreationTest.java",
"test/org/mockitoutil/ExtraMatchers.java"
] | diff --git a/build.gradle b/build.gradle
index 8f7c9ac72f..d78688fc05 100644
--- a/build.gradle
+++ b/build.gradle
@@ -62,8 +62,8 @@ tasks.withType(JavaCompile) {
dependencies {
compile 'net.bytebuddy:byte-buddy:0.6.8'
- provided "junit:junit:4.10"
- compile "org.hamcrest:hamcrest-core:1.1", "org.objenesis:objenesis:2.1"
+ provided "junit:junit:4.11"
+ compile "org.hamcrest:hamcrest-core:1.3", "org.objenesis:objenesis:2.1"
testCompile 'org.ow2.asm:asm:5.0.4'
testCompile fileTree("lib/test")
diff --git a/src/org/mockito/internal/matchers/LocalizedMatcher.java b/src/org/mockito/internal/matchers/LocalizedMatcher.java
index 7aeb79a73f..7adb94fb22 100644
--- a/src/org/mockito/internal/matchers/LocalizedMatcher.java
+++ b/src/org/mockito/internal/matchers/LocalizedMatcher.java
@@ -31,7 +31,11 @@ public void _dont_implement_Matcher___instead_extend_BaseMatcher_() {
public boolean matches(Object item) {
return actualMatcher.matches(item);
}
-
+
+ public void describeMismatch(Object item, Description description) {
+ actualMatcher.describeMismatch(item, description);
+ }
+
public void describeTo(Description description) {
actualMatcher.describeTo(description);
}
@@ -68,4 +72,4 @@ public void captureFrom(Object argument) {
public Matcher getActualMatcher() {
return actualMatcher;
}
-}
\ No newline at end of file
+}
| diff --git a/test/org/mockito/internal/runners/RunnerFactoryTest.java b/test/org/mockito/internal/runners/RunnerFactoryTest.java
index 7620ed7197..4b8ba78074 100644
--- a/test/org/mockito/internal/runners/RunnerFactoryTest.java
+++ b/test/org/mockito/internal/runners/RunnerFactoryTest.java
@@ -37,7 +37,7 @@ public boolean isJUnit45OrHigherAvailable() {
RunnerImpl runner = factory.create(RunnerFactoryTest.class);
//then
- assertThat(runner, is(JUnit44RunnerImpl.class));
+ assertThat(runner, isA(JUnit44RunnerImpl.class));
}
@Test
@@ -54,7 +54,7 @@ public boolean isJUnit45OrHigherAvailable() {
RunnerImpl runner = factory.create(RunnerFactoryTest.class);
//then
- assertThat(runner, is(JUnit45AndHigherRunnerImpl.class));
+ assertThat(runner, isA(JUnit45AndHigherRunnerImpl.class));
}
@Test
@@ -118,4 +118,4 @@ public RunnerImpl newInstance(String runnerClassName, Class<?> constructorParam)
//then
catch (InvocationTargetException e) {}
}
-}
\ No newline at end of file
+}
diff --git a/test/org/mockitousage/basicapi/MocksCreationTest.java b/test/org/mockitousage/basicapi/MocksCreationTest.java
index 533826a6f4..732295a112 100644
--- a/test/org/mockitousage/basicapi/MocksCreationTest.java
+++ b/test/org/mockitousage/basicapi/MocksCreationTest.java
@@ -62,7 +62,7 @@ public void shouldCombineMockNameAndExtraInterfaces() {
//then
assertContains("great mockie", name);
//and
- assertThat(mock, is(List.class));
+ assertThat(mock, isA(List.class));
}
@Test
@@ -100,4 +100,4 @@ public void shouldAllowInlineMockCreation() throws Exception {
when(mock(Set.class).isEmpty()).thenReturn(false);
}
-}
\ No newline at end of file
+}
diff --git a/test/org/mockitoutil/ExtraMatchers.java b/test/org/mockitoutil/ExtraMatchers.java
index bd0fe349ec..bce921ec6e 100644
--- a/test/org/mockitoutil/ExtraMatchers.java
+++ b/test/org/mockitoutil/ExtraMatchers.java
@@ -134,7 +134,7 @@ public void assertValue(Collection value) {
}
public static org.hamcrest.Matcher<java.lang.Object> clazz(java.lang.Class<?> type) {
- return CoreMatchers.is(type);
+ return CoreMatchers.isA(type);
}
public static Assertor hasMethodsInStackTrace(final String ... methods) {
@@ -147,4 +147,4 @@ public void assertValue(Throwable value) {
}
};
}
-}
\ No newline at end of file
+}
| val | train | 2015-06-15T05:19:47 | "2015-06-12T18:54:50Z" | durron597 | train |
mockito/mockito/154_232 | mockito/mockito | mockito/mockito/154 | mockito/mockito/232 | [
"timestamp(timedelta=169205.0, similarity=0.8423210559979228)"
] | 6b5424acebc1bc4ebaca97d6592ade901d1fb838 | 3359a126b5e0a45f084820c615ae007736367121 | [
"What's the progress on this? I'd like to use Mockito with my unit tests and I'm running JUnit 4.11 that is bundled with Eclipse 4.4 that I'm using.\n",
"Is Hamcrest dependency a blocker for using Mockito with Eclipse 4.4 ?\n\n-- Brice\n\nOn Tue, Jan 27, 2015 at 10:10 AM, Tobias Eriksson notifications@github.com\nwrote:\n\n> What's the progress on this? I'd like to use Mockito with my unit tests\n> and I'm running JUnit 4.11 that is bundled with Eclipse 4.4 that I'm using.\n> \n> —\n> Reply to this email directly or view it on GitHub\n> https://github.com/mockito/mockito/issues/154#issuecomment-71613024.\n",
"@bric3 It seems that way. Eclipse 4.4 comes with JUnit 4.11 and Hamcrest 1.3, which apparently doesn't work with Mockito? Therefore when I try to run my JUnit plug-in tests for an Eclipse 4.4 RCP application it doesn't work.\n",
"I use Mockito 1.9.5 and 1.10.16 with JUnit 4.11 and 4.12 combined with Hamcrest 1.3 in several applications and didn't have any issues.\n",
"Fells more of an Eclipse issue, if an IDE cannot work with the project\nclasspath...\n\nThe team / the code is clearly not near any Mockito 2.0 _final_ release.\nAnyway, this task is not even started, and it will target Mockito 2.0 as\nAPI will change.\n",
"@bric3 @martin-g My bad, I made a plugin for Mockito and forgot to add the dependencies to Hamcrest and Objenesis. Seems to work fine now as far as I can tell..\n",
"Would be nice to at least upgrade to hamcrest 1.3 (latest version I think).\n",
"@philipwhiuk Maybe in version 2.0. Maybe we could eventually drop the dependency (at this time nothing yet decided)\n",
"Working on this. We will use hamcrest 1.3, too.\n",
"This is completed on master.\n"
] | [] | "2015-06-15T14:13:09Z" | [
"enhancement",
"1.* incompatible"
] | stop depending on hamcrest internally | In order to avoid compatibility/upgrade problems we will stop depending on hamcrest internally. Hamcrest will be an optional dependency of Mockito.
| [
"build.gradle",
"src/org/mockito/internal/matchers/LocalizedMatcher.java"
] | [
"build.gradle",
"src/org/mockito/internal/matchers/LocalizedMatcher.java"
] | [
"test/org/mockito/internal/runners/RunnerFactoryTest.java",
"test/org/mockitousage/basicapi/MocksCreationTest.java",
"test/org/mockitoutil/ExtraMatchers.java"
] | diff --git a/build.gradle b/build.gradle
index 8f7c9ac72f..d78688fc05 100644
--- a/build.gradle
+++ b/build.gradle
@@ -62,8 +62,8 @@ tasks.withType(JavaCompile) {
dependencies {
compile 'net.bytebuddy:byte-buddy:0.6.8'
- provided "junit:junit:4.10"
- compile "org.hamcrest:hamcrest-core:1.1", "org.objenesis:objenesis:2.1"
+ provided "junit:junit:4.11"
+ compile "org.hamcrest:hamcrest-core:1.3", "org.objenesis:objenesis:2.1"
testCompile 'org.ow2.asm:asm:5.0.4'
testCompile fileTree("lib/test")
diff --git a/src/org/mockito/internal/matchers/LocalizedMatcher.java b/src/org/mockito/internal/matchers/LocalizedMatcher.java
index 7aeb79a73f..7adb94fb22 100644
--- a/src/org/mockito/internal/matchers/LocalizedMatcher.java
+++ b/src/org/mockito/internal/matchers/LocalizedMatcher.java
@@ -31,7 +31,11 @@ public void _dont_implement_Matcher___instead_extend_BaseMatcher_() {
public boolean matches(Object item) {
return actualMatcher.matches(item);
}
-
+
+ public void describeMismatch(Object item, Description description) {
+ actualMatcher.describeMismatch(item, description);
+ }
+
public void describeTo(Description description) {
actualMatcher.describeTo(description);
}
@@ -68,4 +72,4 @@ public void captureFrom(Object argument) {
public Matcher getActualMatcher() {
return actualMatcher;
}
-}
\ No newline at end of file
+}
| diff --git a/test/org/mockito/internal/runners/RunnerFactoryTest.java b/test/org/mockito/internal/runners/RunnerFactoryTest.java
index 7620ed7197..4b8ba78074 100644
--- a/test/org/mockito/internal/runners/RunnerFactoryTest.java
+++ b/test/org/mockito/internal/runners/RunnerFactoryTest.java
@@ -37,7 +37,7 @@ public boolean isJUnit45OrHigherAvailable() {
RunnerImpl runner = factory.create(RunnerFactoryTest.class);
//then
- assertThat(runner, is(JUnit44RunnerImpl.class));
+ assertThat(runner, isA(JUnit44RunnerImpl.class));
}
@Test
@@ -54,7 +54,7 @@ public boolean isJUnit45OrHigherAvailable() {
RunnerImpl runner = factory.create(RunnerFactoryTest.class);
//then
- assertThat(runner, is(JUnit45AndHigherRunnerImpl.class));
+ assertThat(runner, isA(JUnit45AndHigherRunnerImpl.class));
}
@Test
@@ -118,4 +118,4 @@ public RunnerImpl newInstance(String runnerClassName, Class<?> constructorParam)
//then
catch (InvocationTargetException e) {}
}
-}
\ No newline at end of file
+}
diff --git a/test/org/mockitousage/basicapi/MocksCreationTest.java b/test/org/mockitousage/basicapi/MocksCreationTest.java
index 533826a6f4..732295a112 100644
--- a/test/org/mockitousage/basicapi/MocksCreationTest.java
+++ b/test/org/mockitousage/basicapi/MocksCreationTest.java
@@ -62,7 +62,7 @@ public void shouldCombineMockNameAndExtraInterfaces() {
//then
assertContains("great mockie", name);
//and
- assertThat(mock, is(List.class));
+ assertThat(mock, isA(List.class));
}
@Test
@@ -100,4 +100,4 @@ public void shouldAllowInlineMockCreation() throws Exception {
when(mock(Set.class).isEmpty()).thenReturn(false);
}
-}
\ No newline at end of file
+}
diff --git a/test/org/mockitoutil/ExtraMatchers.java b/test/org/mockitoutil/ExtraMatchers.java
index bd0fe349ec..bce921ec6e 100644
--- a/test/org/mockitoutil/ExtraMatchers.java
+++ b/test/org/mockitoutil/ExtraMatchers.java
@@ -134,7 +134,7 @@ public void assertValue(Collection value) {
}
public static org.hamcrest.Matcher<java.lang.Object> clazz(java.lang.Class<?> type) {
- return CoreMatchers.is(type);
+ return CoreMatchers.isA(type);
}
public static Assertor hasMethodsInStackTrace(final String ... methods) {
@@ -147,4 +147,4 @@ public void assertValue(Throwable value) {
}
};
}
-}
\ No newline at end of file
+}
| val | train | 2015-06-15T05:19:47 | "2015-01-04T17:53:45Z" | mockitoguy | train |
mockito/mockito/233_234 | mockito/mockito | mockito/mockito/233 | mockito/mockito/234 | [
"keyword_pr_to_issue"
] | 6b5424acebc1bc4ebaca97d6592ade901d1fb838 | b2de99b33959b6e49dadaaae5f627ead2a20f34f | [
"Is this an OSGI package ?\n",
"Also a general principle when mocking is _to not mock types you don't own_, there's several reasons for that see that [wiki page](https://github.com/mockito/mockito/wiki/How-to-write-good-tests).\n\nHowever the issue is probably true. But I cannot reproduce locally, do you have additional informations like jetty version, jvm version (OpenJDK, hotspot, J9, ...) ?\n",
"yeah, i know about that rule. this is from a really tiny method and i just want to check that it invokes the start method. \n\noracle jdk8_11, jetty 9.2.10\n",
"The `Managed` inner class is package-private: http://grepcode.com/file/repo1.maven.org/maven2/org.eclipse.jetty/jetty-util/9.1.3.v20140225/org/eclipse/jetty/util/component/ContainerLifeCycle.java#ContainerLifeCycle.Managed\n\nThis class should never be accessible from `org.eclipse.jetty.client.HttpClient` or any mock which both live in another package. I assume that you have a version clash on your class path. Creating a mock can trigger lazy class path resolutions that are not even triggered in your production code via the class introspection that is required to create the mock. \n",
"ok but the HttpClient class can be instantiated just fine by calling its constructor\n\nclient = new HttpClient();\n",
"also the managed enum is only used inside ContainerLifeCycle. \n",
"I now see what the problem is. Byte Buddy overrides the public method `ContainerLifeCycle::addBean(Object o, Managed managed)` in order to allow mocking the method call. For this, the mock references the `Managed` class which is however package-private.\n\nWhile this is a rather poorly designed API as the method should itself be package-private as it cannot be used outside of the package, Byte Buddy should be smart enough to figure this out. It is a small fix, I have it ready some time this week. Thanks for reporting!\n",
"thanks. I agree that the package structure and api design of jetty is a bit strange.\n",
"@raphw Thanks for the investigation\n",
"@christophsturm Thanks for the feddback too, note mockito 2.0.0 is still in beta phase\n",
"sure! we will just continue to use 2.0.2-beta for now which works great.\n",
"You can use a more recent beta `2.0.8-beta`, the last version before switching to bytebuddy\n",
"Byte Buddy 0.6.9 is released which should fix the issue. Sorry for the hick-up. (In JCenter, currently synchronizing to Maven Central.)\n",
"No problem, you were blazingly fast !\n"
] | [] | "2015-06-18T13:31:46Z" | [
"bug"
] | mockito 2.0.14 fails to mock jetty httpclient | this fails:
<pre>
import org.eclipse.jetty.client.HttpClient;
HttpClient httpClient = mock(HttpClient.class);
</pre>
(jetty 9.2.10.v20150310)
with mockito 2.0.2-beta i can mock that class without a problem.
stacktrace:
<pre>
java.lang.IllegalAccessError: tried to access class org.eclipse.jetty.util.component.ContainerLifeCycle$Managed from class org.eclipse.jetty.client.HttpClient$MockitoMock$362486671
at org.eclipse.jetty.client.HttpClient$MockitoMock$362486671.<clinit>(Unknown Source)
at sun.reflect.GeneratedSerializationConstructorAccessor2.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Constructor.java:408)
at org.objenesis.instantiator.sun.SunReflectionFactoryInstantiator.newInstance(SunReflectionFactoryInstantiator.java:45)
at org.objenesis.ObjenesisBase.newInstance(ObjenesisBase.java:73)
at org.mockito.internal.creation.instance.ObjenesisInstantiator.newInstance(ObjenesisInstantiator.java:14)
at org.mockito.internal.creation.bytebuddy.ByteBuddyMockMaker.createMock(ByteBuddyMockMaker.java:27)
at org.mockito.internal.util.MockUtil.createMock(MockUtil.java:33)
at org.mockito.internal.MockitoCore.mock(MockitoCore.java:59)
at org.mockito.Mockito.mock(Mockito.java:1392)
at org.mockito.Mockito.mock(Mockito.java:1270)
</pre>
| [
"build.gradle",
"gradle/javadoc.gradle",
"mockmaker/bytebuddy/main/java/org/mockito/internal/creation/bytebuddy/MockBytecodeGenerator.java"
] | [
"build.gradle",
"gradle/javadoc.gradle",
"mockmaker/bytebuddy/main/java/org/mockito/internal/creation/bytebuddy/MockBytecodeGenerator.java"
] | [
"test/org/mockitousage/bugs/creation/PublicMethodInParentWithNonPublicTypeInSignatureTest.java",
"test/org/mockitousage/bugs/creation/api/PublicClass.java",
"test/org/mockitousage/bugs/creation/otherpackage/PublicParentClass.java"
] | diff --git a/build.gradle b/build.gradle
index 8f7c9ac72f..939764ee4f 100644
--- a/build.gradle
+++ b/build.gradle
@@ -60,7 +60,7 @@ tasks.withType(JavaCompile) {
//TODO we should remove all dependencies to checked-in jars
dependencies {
- compile 'net.bytebuddy:byte-buddy:0.6.8'
+ compile 'net.bytebuddy:byte-buddy-dep:0.6.10'
provided "junit:junit:4.10"
compile "org.hamcrest:hamcrest-core:1.1", "org.objenesis:objenesis:2.1"
diff --git a/gradle/javadoc.gradle b/gradle/javadoc.gradle
index 7439273357..c221c6277b 100644
--- a/gradle/javadoc.gradle
+++ b/gradle/javadoc.gradle
@@ -35,8 +35,8 @@ task mockitoJavadoc(type: Javadoc) {
<script type="text/javascript">
var usingOldIE = \$.browser.msie && parseInt(\$.browser.version) < 9;
if(!usingOldIE) {
- \$("head").append("<link rel=\\"shortcut icon\\" href=\\"/favicon.ico?v=cafebabe\\">")
- \$("head", window.parent.document).append("<link rel=\\"shortcut icon\\" href=\\"/favicon.ico?v=cafebabe\\">")
+ \$("head").append("<link rel=\\"shortcut icon\\" href=\\"@{docRoot}/favicon.ico?v=cafebabe\\">")
+ \$("head", window.parent.document).append("<link rel=\\"shortcut icon\\" href=\\"@{docRoot}/favicon.ico?v=cafebabe\\">")
hljs.initHighlightingOnLoad();
injectProjectVersionForJavadocJDK6("Mockito ${project.version} API",
"em#mockito-version-header-javadoc7-header",
diff --git a/mockmaker/bytebuddy/main/java/org/mockito/internal/creation/bytebuddy/MockBytecodeGenerator.java b/mockmaker/bytebuddy/main/java/org/mockito/internal/creation/bytebuddy/MockBytecodeGenerator.java
index d89e4250cb..8d7c42d252 100644
--- a/mockmaker/bytebuddy/main/java/org/mockito/internal/creation/bytebuddy/MockBytecodeGenerator.java
+++ b/mockmaker/bytebuddy/main/java/org/mockito/internal/creation/bytebuddy/MockBytecodeGenerator.java
@@ -1,21 +1,24 @@
package org.mockito.internal.creation.bytebuddy;
-import java.util.Random;
-import org.mockito.internal.creation.bytebuddy.ByteBuddyCrossClassLoaderSerializationSupport.CrossClassLoaderSerializableMock;
-import org.mockito.internal.creation.util.SearchingClassLoader;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.ClassFileVersion;
-import net.bytebuddy.description.modifier.FieldManifestation;
-import net.bytebuddy.description.modifier.Ownership;
-import net.bytebuddy.description.modifier.Visibility;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.dynamic.loading.ClassLoadingStrategy;
import net.bytebuddy.dynamic.scaffold.subclass.ConstructorStrategy;
-import net.bytebuddy.implementation.FieldAccessor;
-import net.bytebuddy.implementation.MethodDelegation;
import net.bytebuddy.implementation.attribute.MethodAttributeAppender;
import net.bytebuddy.implementation.attribute.TypeAttributeAppender;
-import net.bytebuddy.matcher.ElementMatchers;
+import org.mockito.internal.creation.bytebuddy.ByteBuddyCrossClassLoaderSerializationSupport.CrossClassLoaderSerializableMock;
+import org.mockito.internal.creation.util.SearchingClassLoader;
+
+import java.util.Random;
+
+import static net.bytebuddy.description.modifier.FieldManifestation.FINAL;
+import static net.bytebuddy.description.modifier.Ownership.STATIC;
+import static net.bytebuddy.description.modifier.Visibility.PRIVATE;
+import static net.bytebuddy.implementation.FieldAccessor.ofBeanProperty;
+import static net.bytebuddy.implementation.MethodDelegation.to;
+import static net.bytebuddy.implementation.MethodDelegation.toInstanceField;
+import static net.bytebuddy.matcher.ElementMatchers.*;
class MockBytecodeGenerator {
private final ByteBuddy byteBuddy;
@@ -31,20 +34,20 @@ public MockBytecodeGenerator() {
}
public <T> Class<? extends T> generateMockClass(MockFeatures<T> features) {
- DynamicType.Builder<T> builder = byteBuddy.subclass(features.mockedType, ConstructorStrategy.Default.IMITATE_SUPER_TYPE)
- .name(nameFor(features.mockedType))
- .implement(features.interfaces.toArray(new Class<?>[features.interfaces.size()]))
- .method(ElementMatchers.any()).intercept(MethodDelegation
- .toInstanceField(MockMethodInterceptor.class, "mockitoInterceptor")
- .filter(ElementMatchers.isDeclaredBy(MockMethodInterceptor.class)))
- .implement(MockMethodInterceptor.MockAccess.class).intercept(FieldAccessor.ofBeanProperty())
- .method(ElementMatchers.isHashCode()).intercept(MethodDelegation.to(MockMethodInterceptor.ForHashCode.class))
- .method(ElementMatchers.isEquals()).intercept(MethodDelegation.to(MockMethodInterceptor.ForEquals.class))
- .defineField("serialVersionUID", long.class, Ownership.STATIC, Visibility.PRIVATE, FieldManifestation.FINAL).value(42L);
- if (features.crossClassLoaderSerializable) {
- builder = builder.implement(CrossClassLoaderSerializableMock.class)
- .intercept(MethodDelegation.to(MockMethodInterceptor.ForWriteReplace.class));
- }
+ DynamicType.Builder<T> builder =
+ byteBuddy.subclass(features.mockedType, ConstructorStrategy.Default.IMITATE_SUPER_TYPE)
+ .name(nameFor(features.mockedType))
+ .implement(features.interfaces.toArray(new Class<?>[features.interfaces.size()]))
+ .method(any()).intercept(toInstanceField(MockMethodInterceptor.class, "mockitoInterceptor")
+ .filter(isDeclaredBy(MockMethodInterceptor.class)))
+ .implement(MockMethodInterceptor.MockAccess.class).intercept(ofBeanProperty())
+ .method(isHashCode()).intercept(to(MockMethodInterceptor.ForHashCode.class))
+ .method(isEquals()).intercept(to(MockMethodInterceptor.ForEquals.class))
+ .defineField("serialVersionUID", long.class, STATIC, PRIVATE, FINAL).value(42L);
+ if (features.crossClassLoaderSerializable) {
+ builder = builder.implement(CrossClassLoaderSerializableMock.class)
+ .intercept(to(MockMethodInterceptor.ForWriteReplace.class));
+ }
Class<?>[] allMockedTypes = new Class<?>[features.interfaces.size() + 1];
allMockedTypes[0] = features.mockedType;
// System.arraycopy(interfaces.toArray(), 0, allMockedTypes, 1, interfaces.size());
@@ -53,8 +56,8 @@ public <T> Class<? extends T> generateMockClass(MockFeatures<T> features) {
allMockedTypes[index++] = type;
}
return builder.make()
- .load(SearchingClassLoader.combineLoadersOf(allMockedTypes), ClassLoadingStrategy.Default.INJECTION)
- .getLoaded();
+ .load(SearchingClassLoader.combineLoadersOf(allMockedTypes), ClassLoadingStrategy.Default.INJECTION)
+ .getLoaded();
}
// TODO inspect naming strategy (for OSGI, signed package, java.* (and bootstrap classes), etc...)
| diff --git a/test/org/mockitousage/bugs/creation/PublicMethodInParentWithNonPublicTypeInSignatureTest.java b/test/org/mockitousage/bugs/creation/PublicMethodInParentWithNonPublicTypeInSignatureTest.java
new file mode 100644
index 0000000000..9d4e340bf3
--- /dev/null
+++ b/test/org/mockitousage/bugs/creation/PublicMethodInParentWithNonPublicTypeInSignatureTest.java
@@ -0,0 +1,22 @@
+package org.mockitousage.bugs.creation;
+
+
+import org.junit.Test;
+import org.mockito.Mockito;
+import org.mockitousage.bugs.creation.api.PublicClass;
+
+// see GH-233
+public class PublicMethodInParentWithNonPublicTypeInSignatureTest {
+
+ private Object ref;
+
+ @Test
+ public void java_object_creation() throws Exception {
+ ref = new PublicClass();
+ }
+
+ @Test
+ public void should_not_fail_when_instantiating() throws Exception {
+ ref = Mockito.mock(PublicClass.class);
+ }
+}
diff --git a/test/org/mockitousage/bugs/creation/api/PublicClass.java b/test/org/mockitousage/bugs/creation/api/PublicClass.java
new file mode 100644
index 0000000000..243036a0d4
--- /dev/null
+++ b/test/org/mockitousage/bugs/creation/api/PublicClass.java
@@ -0,0 +1,6 @@
+package org.mockitousage.bugs.creation.api;
+
+import org.mockitousage.bugs.creation.otherpackage.PublicParentClass;
+
+public class PublicClass extends PublicParentClass {
+}
diff --git a/test/org/mockitousage/bugs/creation/otherpackage/PublicParentClass.java b/test/org/mockitousage/bugs/creation/otherpackage/PublicParentClass.java
new file mode 100644
index 0000000000..8f560d4645
--- /dev/null
+++ b/test/org/mockitousage/bugs/creation/otherpackage/PublicParentClass.java
@@ -0,0 +1,6 @@
+package org.mockitousage.bugs.creation.otherpackage;
+
+public class PublicParentClass {
+ public void method_with_non_public_argument(PackageLocalArg arg) { }
+ static class PackageLocalArg { }
+}
| val | train | 2015-06-15T05:19:47 | "2015-06-18T06:24:45Z" | christophsturm | train |
mockito/mockito/220_235 | mockito/mockito | mockito/mockito/220 | mockito/mockito/235 | [
"keyword_pr_to_issue"
] | ad0b7e88056eb662ead86885667be6055708e67d | e696f60bcfc5bbcffb59f68f4981f1ef9e8574e3 | [
"Can you try with 2.0.11-beta ?\n",
"Same problem with 2.0.11-beta (in fact, I started with that version, and then decremented one by one till the problem was gone).\n",
"If I had to make a (somewhat) educated guess I would say it is most likely related to 3b445aa057ada4e64b096634b011eab399f03f56\n",
"It's not really that commit, it probably have to do with the change from CGLIB to ByteBuddy. I cannot reproduce locally, can you craft a reproducible test ?\n",
"MonitorTaskScheduler.java: \n\n``` java\npublic class MonitorTaskScheduler\n{\n private final Map<ScheduledFuture<?>, MonitorTask> futureToTaskMap;\n private final ScheduledExecutorService executor;\n\n public MonitorTaskScheduler()\n {\n futureToTaskMap = new ConcurrentHashMap<>();\n executor = (ScheduledExecutorService) getExecutorService();\n }\n\n @VisibleForTesting\n ExecutorService getExecutorService()\n {\n return new MonitorTaskExecutor(this);\n }\n}\n```\n\nMonitorTaskSchedulerTest.java:\n\n``` java\n@Spy\nMonitorTaskScheduler monitorTaskScheduler;\n\n@Before\npublic void setUp()\n{\n MockitoAnnotations.initMocks(this);\n doReturn(new SynchronousExecutor()).when(monitorTaskScheduler).getExecutorService();\n}\n\n@Test\npublic void test()\n{\n monitorTaskScheduler.schedule(() -> { System.out.println(\"Task\") });\n}\n\npublic class SynchronousExecutor extends AbstractExecutorService\n{\n private volatile boolean shutdown;\n\n public void shutdown()\n {\n shutdown = true;\n }\n\n public List<Runnable> shutdownNow()\n {\n return null;\n }\n\n public boolean isShutdown()\n {\n return shutdown;\n }\n\n public boolean isTerminated()\n {\n return shutdown;\n }\n\n public boolean awaitTermination(long time, TimeUnit unit) throws InterruptedException\n {\n return true;\n }\n\n public void execute(Runnable runnable)\n {\n runnable.run();\n }\n\n}\n```\n",
"I've identified an issue but the given code is incomplete and I don't get the same stacktrace, so it may be another issue.\n\nHere's mine : \n\n``` java\npublic class ConstrucotrInvokingMethodShouldWorkTest {\n @Spy HasConstructorInvokingMethod hasConstructorInvokingMethod;\n\n @Test\n public void should_be_able_to_create_spy() throws Exception {\n MockitoAnnotations.initMocks(this);\n }\n\n private static class HasConstructorInvokingMethod {\n public HasConstructorInvokingMethod() {\n someMethod();\n }\n void someMethod() { }\n }\n}\n```\n\nIn the meantime two workaround, sticks to an older version, or modify the code so it doesn't call methods in the constructor, which may indicate the design is wrong in OOP (builders or factory to the rescue).\n",
"Actually there maybe a better workaround, using the `Mockito.spy()` factory method.\n\n``` java\nclass MonitorTaskSchedulerTest {\n\n// @Spy\nMonitorTaskScheduler monitorTaskScheduler = spy(new MinitorTaskScheduler());\n```\n\nThis even works with `@InjectMocks`\n",
"Sorry for not providing a complete example..was trying to copy and paste stuff from difference sources for simplification purposes. Glad you were at least able to identify an issue out of it. I will take your suggestions and do what I can. Thanks.\n",
"You're welcome, thanks for testing betas ;)\n",
"2d036ec fixed my original issue indeed! Thanks so much, great work.\n"
] | [] | "2015-06-19T23:51:30Z" | [
"bug"
] | 2.0.8-beta -> 2.0.9-beta 'Unable to initialize @Spy annotated field | No test failures when using 2.0.8-beta, but when incrementing to 2.0.9-beta, the following error occurs:
```
org.mockito.exceptions.base.MockitoException: Unable to initialize @Spy annotated field 'monitorTaskScheduler'.
Unable to create mock instance of type 'MonitorTaskScheduler'
at net.project.dash.monitor.MonitorTaskScheduler$MockitoMock$1184625981.getExecutorService(Unknown Source)
at net.project.dash.monitor.MonitorTaskScheduler.<init>(MonitorTaskScheduler.java:39)
at net.project.dash.monitor.MonitorTaskScheduler$MockitoMock$1184625981.<init>(Unknown Source)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
at org.mockito.internal.creation.instance.ConstructorInstantiator.invokeConstructor(ConstructorInstantiator.java:42)
at org.mockito.internal.creation.instance.ConstructorInstantiator.noArgConstructor(ConstructorInstantiator.java:66)
at org.mockito.internal.creation.instance.ConstructorInstantiator.newInstance(ConstructorInstantiator.java:17)
at org.mockito.internal.creation.bytebuddy.ByteBuddyMockMaker.createMock(ByteBuddyMockMaker.java:27)
at org.mockito.internal.util.MockUtil.createMock(MockUtil.java:33)
at org.mockito.internal.MockitoCore.mock(MockitoCore.java:59)
at org.mockito.Mockito.mock(Mockito.java:1284)
at org.mockito.internal.configuration.SpyAnnotationEngine.newSpyInstance(SpyAnnotationEngine.java:117)
at org.mockito.internal.configuration.SpyAnnotationEngine.process(SpyAnnotationEngine.java:67)
at org.mockito.internal.configuration.InjectingAnnotationEngine.processIndependentAnnotations(InjectingAnnotationEngine.java:73)
at org.mockito.internal.configuration.InjectingAnnotationEngine.process(InjectingAnnotationEngine.java:55)
at org.mockito.MockitoAnnotations.initMocks(MockitoAnnotations.java:108)
at net.project.dash.monitor.MonitorTaskSchedulerTest.setUp(MonitorTaskSchedulerTest.java:38)
```
Relevant code (MonitorTaskSchedulerTest.java)
``` java
@Spy
MonitorTaskScheduler monitorTaskScheduler;
@Before
public void setUp()
{
MockitoAnnotations.initMocks(this);
}
```
Relevant code (MonitorTaskScheduler.java)
``` java
public class MonitorTaskScheduler
{
public MonitorTaskScheduler()
{
this.futureToTaskMap = new ConcurrentHashMap<>();
}
}
```
| [
"gradle/javadoc.gradle",
"mockmaker/bytebuddy/main/java/org/mockito/internal/creation/bytebuddy/ByteBuddyMockMaker.java",
"mockmaker/bytebuddy/main/java/org/mockito/internal/creation/bytebuddy/MockBytecodeGenerator.java",
"mockmaker/bytebuddy/main/java/org/mockito/internal/creation/bytebuddy/MockMethodInterceptor.java"
] | [
"gradle/javadoc.gradle",
"mockmaker/bytebuddy/main/java/org/mockito/internal/creation/bytebuddy/ByteBuddyMockMaker.java",
"mockmaker/bytebuddy/main/java/org/mockito/internal/creation/bytebuddy/MockBytecodeGenerator.java",
"mockmaker/bytebuddy/main/java/org/mockito/internal/creation/bytebuddy/MockMethodInterceptor.java"
] | [
"test/org/mockitousage/bugs/ConstructorInvokingMethodShouldNotRaiseExceptionTest.java"
] | diff --git a/gradle/javadoc.gradle b/gradle/javadoc.gradle
index c221c6277b..716fb6a102 100644
--- a/gradle/javadoc.gradle
+++ b/gradle/javadoc.gradle
@@ -35,8 +35,8 @@ task mockitoJavadoc(type: Javadoc) {
<script type="text/javascript">
var usingOldIE = \$.browser.msie && parseInt(\$.browser.version) < 9;
if(!usingOldIE) {
- \$("head").append("<link rel=\\"shortcut icon\\" href=\\"@{docRoot}/favicon.ico?v=cafebabe\\">")
- \$("head", window.parent.document).append("<link rel=\\"shortcut icon\\" href=\\"@{docRoot}/favicon.ico?v=cafebabe\\">")
+ \$("head").append("<link rel=\\"shortcut icon\\" href=\\"{@docRoot}/favicon.ico?v=cafebabe\\">")
+ \$("head", window.parent.document).append("<link rel=\\"shortcut icon\\" href=\\"{@docRoot}/favicon.ico?v=cafebabe\\">")
hljs.initHighlightingOnLoad();
injectProjectVersionForJavadocJDK6("Mockito ${project.version} API",
"em#mockito-version-header-javadoc7-header",
diff --git a/mockmaker/bytebuddy/main/java/org/mockito/internal/creation/bytebuddy/ByteBuddyMockMaker.java b/mockmaker/bytebuddy/main/java/org/mockito/internal/creation/bytebuddy/ByteBuddyMockMaker.java
index 1ec76d2c6f..2875df319d 100644
--- a/mockmaker/bytebuddy/main/java/org/mockito/internal/creation/bytebuddy/ByteBuddyMockMaker.java
+++ b/mockmaker/bytebuddy/main/java/org/mockito/internal/creation/bytebuddy/ByteBuddyMockMaker.java
@@ -1,8 +1,8 @@
package org.mockito.internal.creation.bytebuddy;
-import static org.mockito.internal.util.StringJoiner.join;
import org.mockito.exceptions.base.MockitoException;
import org.mockito.internal.InternalMockHandler;
+import org.mockito.internal.creation.bytebuddy.MockMethodInterceptor.MockAccess;
import org.mockito.internal.creation.instance.Instantiator;
import org.mockito.internal.creation.instance.InstantiatorProvider;
import org.mockito.invocation.MockHandler;
@@ -10,6 +10,8 @@
import org.mockito.mock.SerializableMode;
import org.mockito.plugins.MockMaker;
+import static org.mockito.internal.util.StringJoiner.join;
+
public class ByteBuddyMockMaker implements MockMaker {
private final CachingMockBytecodeGenerator cachingMockBytecodeGenerator;
@@ -25,7 +27,7 @@ public <T> T createMock(MockCreationSettings<T> settings, MockHandler handler) {
T mockInstance = null;
try {
mockInstance = instantiator.newInstance(mockedProxyType);
- MockMethodInterceptor.MockAccess mockAccess = (MockMethodInterceptor.MockAccess) mockInstance;
+ MockAccess mockAccess = (MockAccess) mockInstance;
mockAccess.setMockitoInterceptor(new MockMethodInterceptor(asInternalMockHandler(handler), settings));
return ensureMockIsAssignableToMockedType(settings, mockInstance);
@@ -75,14 +77,14 @@ private static String describeClass(Object instance) {
}
public MockHandler getHandler(Object mock) {
- if (!(mock instanceof MockMethodInterceptor.MockAccess)) {
+ if (!(mock instanceof MockAccess)) {
return null;
}
- return ((MockMethodInterceptor.MockAccess) mock).getMockitoInterceptor().getMockHandler();
+ return ((MockAccess) mock).getMockitoInterceptor().getMockHandler();
}
public void resetMock(Object mock, MockHandler newHandler, MockCreationSettings settings) {
- ((MockMethodInterceptor.MockAccess) mock).setMockitoInterceptor(
+ ((MockAccess) mock).setMockitoInterceptor(
new MockMethodInterceptor(asInternalMockHandler(newHandler), settings)
);
}
diff --git a/mockmaker/bytebuddy/main/java/org/mockito/internal/creation/bytebuddy/MockBytecodeGenerator.java b/mockmaker/bytebuddy/main/java/org/mockito/internal/creation/bytebuddy/MockBytecodeGenerator.java
index 8d7c42d252..e4ae2bf8f9 100644
--- a/mockmaker/bytebuddy/main/java/org/mockito/internal/creation/bytebuddy/MockBytecodeGenerator.java
+++ b/mockmaker/bytebuddy/main/java/org/mockito/internal/creation/bytebuddy/MockBytecodeGenerator.java
@@ -5,9 +5,17 @@
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.dynamic.loading.ClassLoadingStrategy;
import net.bytebuddy.dynamic.scaffold.subclass.ConstructorStrategy;
+import net.bytebuddy.implementation.FieldAccessor;
+import net.bytebuddy.implementation.Implementation;
+import net.bytebuddy.implementation.MethodDelegation;
import net.bytebuddy.implementation.attribute.MethodAttributeAppender;
import net.bytebuddy.implementation.attribute.TypeAttributeAppender;
+import net.bytebuddy.implementation.bind.annotation.FieldProxy;
import org.mockito.internal.creation.bytebuddy.ByteBuddyCrossClassLoaderSerializationSupport.CrossClassLoaderSerializableMock;
+import org.mockito.internal.creation.bytebuddy.MockMethodInterceptor.DispatcherDefaultingToRealMethod;
+import org.mockito.internal.creation.bytebuddy.MockMethodInterceptor.DispatcherDefaultingToRealMethod.FieldGetter;
+import org.mockito.internal.creation.bytebuddy.MockMethodInterceptor.DispatcherDefaultingToRealMethod.FieldSetter;
+import org.mockito.internal.creation.bytebuddy.MockMethodInterceptor.MockAccess;
import org.mockito.internal.creation.util.SearchingClassLoader;
import java.util.Random;
@@ -15,21 +23,25 @@
import static net.bytebuddy.description.modifier.FieldManifestation.FINAL;
import static net.bytebuddy.description.modifier.Ownership.STATIC;
import static net.bytebuddy.description.modifier.Visibility.PRIVATE;
-import static net.bytebuddy.implementation.FieldAccessor.ofBeanProperty;
import static net.bytebuddy.implementation.MethodDelegation.to;
-import static net.bytebuddy.implementation.MethodDelegation.toInstanceField;
-import static net.bytebuddy.matcher.ElementMatchers.*;
+import static net.bytebuddy.matcher.ElementMatchers.any;
+import static net.bytebuddy.matcher.ElementMatchers.isEquals;
+import static net.bytebuddy.matcher.ElementMatchers.isHashCode;
class MockBytecodeGenerator {
private final ByteBuddy byteBuddy;
private final Random random;
+ private final Implementation toDispatcher;
public MockBytecodeGenerator() {
byteBuddy = new ByteBuddy(ClassFileVersion.JAVA_V5)
-// .withIgnoredMethods(isBridge())
.withDefaultMethodAttributeAppender(MethodAttributeAppender.ForInstrumentedMethod.INSTANCE)
.withAttribute(TypeAttributeAppender.ForSuperType.INSTANCE);
+ // Necessary for ConstructorInstantiator
+ toDispatcher = MethodDelegation.to(DispatcherDefaultingToRealMethod.class)
+ .appendParameterBinder(FieldProxy.Binder.install(FieldGetter.class,
+ FieldSetter.class));
random = new Random();
}
@@ -38,9 +50,9 @@ public <T> Class<? extends T> generateMockClass(MockFeatures<T> features) {
byteBuddy.subclass(features.mockedType, ConstructorStrategy.Default.IMITATE_SUPER_TYPE)
.name(nameFor(features.mockedType))
.implement(features.interfaces.toArray(new Class<?>[features.interfaces.size()]))
- .method(any()).intercept(toInstanceField(MockMethodInterceptor.class, "mockitoInterceptor")
- .filter(isDeclaredBy(MockMethodInterceptor.class)))
- .implement(MockMethodInterceptor.MockAccess.class).intercept(ofBeanProperty())
+ .method(any()).intercept(toDispatcher)
+ .defineField("mockitoInterceptor", MockMethodInterceptor.class, PRIVATE)
+ .implement(MockAccess.class).intercept(FieldAccessor.ofBeanProperty())
.method(isHashCode()).intercept(to(MockMethodInterceptor.ForHashCode.class))
.method(isEquals()).intercept(to(MockMethodInterceptor.ForEquals.class))
.defineField("serialVersionUID", long.class, STATIC, PRIVATE, FINAL).value(42L);
@@ -48,18 +60,19 @@ public <T> Class<? extends T> generateMockClass(MockFeatures<T> features) {
builder = builder.implement(CrossClassLoaderSerializableMock.class)
.intercept(to(MockMethodInterceptor.ForWriteReplace.class));
}
- Class<?>[] allMockedTypes = new Class<?>[features.interfaces.size() + 1];
- allMockedTypes[0] = features.mockedType;
-// System.arraycopy(interfaces.toArray(), 0, allMockedTypes, 1, interfaces.size());
- int index = 1;
- for (Class<?> type : features.interfaces) {
- allMockedTypes[index++] = type;
- }
return builder.make()
- .load(SearchingClassLoader.combineLoadersOf(allMockedTypes), ClassLoadingStrategy.Default.INJECTION)
+ .load(SearchingClassLoader.combineLoadersOf(allMockedTypes(features)), ClassLoadingStrategy.Default.INJECTION)
.getLoaded();
}
+ private <T> Class<?>[] allMockedTypes(MockFeatures<T> features) {
+ Class<?>[] allMockedTypes = new Class<?>[features.interfaces.size() + 1];
+ allMockedTypes[0] = features.mockedType;
+ System.arraycopy(features.interfaces.toArray(), 0,
+ (Object[]) allMockedTypes, 1, features.interfaces.size());
+ return allMockedTypes;
+ }
+
// TODO inspect naming strategy (for OSGI, signed package, java.* (and bootstrap classes), etc...)
private String nameFor(Class<?> type) {
String typeName = type.getName();
diff --git a/mockmaker/bytebuddy/main/java/org/mockito/internal/creation/bytebuddy/MockMethodInterceptor.java b/mockmaker/bytebuddy/main/java/org/mockito/internal/creation/bytebuddy/MockMethodInterceptor.java
index c70d849dc3..3e55e6cb0d 100644
--- a/mockmaker/bytebuddy/main/java/org/mockito/internal/creation/bytebuddy/MockMethodInterceptor.java
+++ b/mockmaker/bytebuddy/main/java/org/mockito/internal/creation/bytebuddy/MockMethodInterceptor.java
@@ -1,9 +1,6 @@
package org.mockito.internal.creation.bytebuddy;
-import java.io.ObjectStreamException;
-import java.io.Serializable;
-import java.lang.reflect.Method;
-import java.util.concurrent.Callable;
+import net.bytebuddy.implementation.bind.annotation.*;
import org.mockito.internal.InternalMockHandler;
import org.mockito.internal.creation.DelegatingMethod;
import org.mockito.internal.invocation.MockitoMethod;
@@ -11,14 +8,11 @@
import org.mockito.internal.progress.SequenceNumber;
import org.mockito.invocation.MockHandler;
import org.mockito.mock.MockCreationSettings;
-import net.bytebuddy.implementation.bind.annotation.AllArguments;
-import net.bytebuddy.implementation.bind.annotation.Argument;
-import net.bytebuddy.implementation.bind.annotation.BindingPriority;
-import net.bytebuddy.implementation.bind.annotation.DefaultCall;
-import net.bytebuddy.implementation.bind.annotation.Origin;
-import net.bytebuddy.implementation.bind.annotation.RuntimeType;
-import net.bytebuddy.implementation.bind.annotation.SuperCall;
-import net.bytebuddy.implementation.bind.annotation.This;
+
+import java.io.ObjectStreamException;
+import java.io.Serializable;
+import java.lang.reflect.Method;
+import java.util.concurrent.Callable;
public class MockMethodInterceptor implements Serializable {
@@ -122,8 +116,53 @@ public static Object doWriteReplace(@This MockAccess thiz) throws ObjectStreamEx
}
}
- public static interface MockAccess {
+ public interface MockAccess {
MockMethodInterceptor getMockitoInterceptor();
void setMockitoInterceptor(MockMethodInterceptor mockMethodInterceptor);
}
+
+ public static class DispatcherDefaultingToRealMethod {
+ public interface FieldGetter<T> {
+ T getValue();
+ }
+ public interface FieldSetter<T> {
+ void setValue(T value);
+ }
+
+ @RuntimeType
+ @BindingPriority(BindingPriority.DEFAULT * 2)
+ public static Object interceptSuperCallable(@This Object mock,
+ @FieldProxy("mockitoInterceptor") FieldGetter<MockMethodInterceptor> fieldGetter,
+ @Origin Method invokedMethod,
+ @AllArguments Object[] arguments,
+ @SuperCall(serializableProxy = true) Callable<?> superCall) throws Throwable {
+ MockMethodInterceptor interceptor = fieldGetter.getValue();
+ if (interceptor == null) {
+ return superCall.call();
+ }
+ return interceptor.doIntercept(
+ mock,
+ invokedMethod,
+ arguments,
+ new InterceptedInvocation.SuperMethod.FromCallable(superCall)
+ );
+ }
+
+ @RuntimeType
+ public static Object interceptAbstract(@This Object mock,
+ @FieldProxy("mockitoInterceptor") FieldGetter<MockMethodInterceptor> fieldGetter,
+ @Origin(cache = true) Method invokedMethod,
+ @AllArguments Object[] arguments) throws Throwable {
+ MockMethodInterceptor interceptor = fieldGetter.getValue();
+ if (interceptor == null) {
+ return null;
+ }
+ return interceptor.doIntercept(
+ mock,
+ invokedMethod,
+ arguments,
+ InterceptedInvocation.SuperMethod.IsIllegal.INSTANCE
+ );
+ }
+ }
}
| diff --git a/test/org/mockitousage/bugs/ConstructorInvokingMethodShouldNotRaiseExceptionTest.java b/test/org/mockitousage/bugs/ConstructorInvokingMethodShouldNotRaiseExceptionTest.java
new file mode 100644
index 0000000000..af85e88f15
--- /dev/null
+++ b/test/org/mockitousage/bugs/ConstructorInvokingMethodShouldNotRaiseExceptionTest.java
@@ -0,0 +1,46 @@
+package org.mockitousage.bugs;
+
+import org.junit.Test;
+import org.junit.experimental.runners.Enclosed;
+import org.junit.runner.RunWith;
+import org.mockito.MockitoAnnotations;
+import org.mockito.Spy;
+
+@RunWith(Enclosed.class)
+public class ConstructorInvokingMethodShouldNotRaiseExceptionTest {
+
+ public static class WithDumbMethod {
+ @Spy
+ HasConstructorInvokingMethod hasConstructorInvokingMethod;
+
+ @Test
+ public void should_be_able_to_create_spy() throws Exception {
+ MockitoAnnotations.initMocks(this);
+ }
+
+ private static class HasConstructorInvokingMethod {
+ public HasConstructorInvokingMethod() { someMethod(); }
+
+ void someMethod() { }
+ }
+ }
+
+ public static class UsingMethodResult {
+ @Spy
+ HasConstructorInvokingMethod hasConstructorInvokingMethod;
+
+ @Test
+ public void should_be_able_to_create_spy() throws Exception {
+ MockitoAnnotations.initMocks(this);
+ }
+
+ private static class HasConstructorInvokingMethod {
+ private final boolean doesIt;
+ public HasConstructorInvokingMethod() {
+ doesIt = someMethod().contains("yup");
+ }
+
+ String someMethod() { return "tada!"; }
+ }
+ }
+}
| train | train | 2015-06-18T18:49:16 | "2015-06-04T07:29:05Z" | brcolow | train |
mockito/mockito/244_247 | mockito/mockito | mockito/mockito/244 | mockito/mockito/247 | [
"timestamp(timedelta=18.0, similarity=0.9288212853466791)"
] | dba9d50911870431ba891be8b9438ec326811482 | 4486887c02c436f12223e198818faa2544a16f9b | [
"Well spotted. We'll fix it. Any chance for PR?\n",
"Sorry I should really have sent a PR with the bug report.\n\nI'm recently pretty swamped. Spent a day and an evening trying to upgrade Mockito (thought it was a low-hanging fruit) but then had to draw the line because fixing all the breakage in Google's codebase had started to look like a sizable project.\n",
"Thanks a lot for the reports. This is great stuff. Thank you for pushing\nmockito upgrade at G. This helps a lot because you have already fleshed out\na couple of bugs.\n\nOn Thu, Jul 2, 2015, 12:03 Ben Yu notifications@github.com wrote:\n\n> Sorry I should really have sent a PR with the bug report.\n> \n> I'm recently pretty swamped. Spent a day and an evening trying to upgrade\n> Mockito (thought it was a low-hanging fruit) but then had to draw the line\n> because fixing all the breakage in Google's codebase had started to look\n> like a sizable project.\n> \n> —\n> Reply to this email directly or view it on GitHub\n> https://github.com/mockito/mockito/issues/244#issuecomment-118131389.\n",
"Closed via fa0ebda114afefedea340077b60bc1d8474c7767\n"
] | [] | "2015-07-07T22:20:02Z" | [
"bug"
] | StackOverflowError in MockitoSerializationIssue.java | In MockitoSerializationIssue.filterStackTrace(), it calls `filter.filter(this)`, which then calls getStackTrace() again, causing an infinite recursion.
| [
"src/org/mockito/exceptions/base/MockitoSerializationIssue.java"
] | [
"src/org/mockito/exceptions/base/MockitoSerializationIssue.java"
] | [
"test/org/mockito/exceptions/base/MockitoSerializationIssueTest.java"
] | diff --git a/src/org/mockito/exceptions/base/MockitoSerializationIssue.java b/src/org/mockito/exceptions/base/MockitoSerializationIssue.java
index 67a7387016..458b56dcc6 100644
--- a/src/org/mockito/exceptions/base/MockitoSerializationIssue.java
+++ b/src/org/mockito/exceptions/base/MockitoSerializationIssue.java
@@ -30,12 +30,6 @@ public MockitoSerializationIssue(String message, Exception cause) {
filterStackTrace();
}
- @Override
- public StackTraceElement[] getStackTrace() {
- filterStackTrace();
- return super.getStackTrace();
- }
-
private void filterStackTrace() {
unfilteredStackTrace = super.getStackTrace();
| diff --git a/test/org/mockito/exceptions/base/MockitoSerializationIssueTest.java b/test/org/mockito/exceptions/base/MockitoSerializationIssueTest.java
new file mode 100644
index 0000000000..8e81b00939
--- /dev/null
+++ b/test/org/mockito/exceptions/base/MockitoSerializationIssueTest.java
@@ -0,0 +1,41 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.exceptions.base;
+
+import org.junit.Test;
+import org.mockito.internal.configuration.ConfigurationAccess;
+import org.mockitoutil.TestBase;
+
+import java.util.Arrays;
+
+public class MockitoSerializationIssueTest extends TestBase {
+
+ @Test
+ public void shouldFilterOutTestClassFromStacktraceWhenCleanFlagIsTrue() {
+ // given
+ ConfigurationAccess.getConfig().overrideCleansStackTrace(true);
+
+ // when
+ MockitoSerializationIssue issue = new MockitoSerializationIssue("msg", new Exception("cause"));
+
+ // then
+ assertContains("MockitoSerializationIssueTest", Arrays.toString(issue.getUnfilteredStackTrace()));
+ assertNotContains("MockitoSerializationIssueTest", Arrays.toString(issue.getStackTrace()));
+ }
+
+ @Test
+ public void shouldKeepExecutingClassInStacktraceWhenCleanFlagIsFalse() {
+ // given
+ ConfigurationAccess.getConfig().overrideCleansStackTrace(false);
+
+ // when
+ MockitoSerializationIssue issue = new MockitoSerializationIssue("msg", new Exception("cause"));
+
+ // then
+ assertContains("MockitoSerializationIssueTest", Arrays.toString(issue.getUnfilteredStackTrace()));
+ assertContains("MockitoSerializationIssueTest", Arrays.toString(issue.getStackTrace()));
+ }
+}
| test | train | 2015-06-30T07:20:28 | "2015-06-26T19:20:58Z" | fluentfuture | train |
mockito/mockito/251_252 | mockito/mockito | mockito/mockito/251 | mockito/mockito/252 | [
"timestamp(timedelta=0.0, similarity=0.9095102005639756)"
] | 037b0dbc2097f0d5aee0200d22bd46a79f8a34d3 | 5f4dbe782093df70566ff0ee1bacc3baf5aa1158 | [] | [] | "2015-07-08T15:20:46Z" | [
"refactoring"
] | Unit tests improvements: migrate from legacy FEST Assert code to AssertJ | Triggered by #250.
| [
"build.gradle"
] | [
"build.gradle"
] | [
"subprojects/testng/src/test/java/org/mockitousage/testng/AnnotatedFieldsShouldBeInitializedByMockitoTestNGListenerTest.java",
"subprojects/testng/src/test/java/org/mockitousage/testng/CaptorAnnotatedFieldShouldBeClearedTest.java",
"subprojects/testng/src/test/java/org/mockitousage/testng/ConfigurationMethodTest.java",
"subprojects/testng/src/test/java/org/mockitousage/testng/DontResetMocksIfNoListenerTest.java",
"subprojects/testng/src/test/java/org/mockitousage/testng/EnsureMocksAreInitializedBeforeBeforeClassMethodTest.java",
"subprojects/testng/src/test/java/org/mockitousage/testng/InitializeChildTestWhenParentHasListenerTest.java",
"subprojects/testng/src/test/java/org/mockitousage/testng/MockFieldsShouldBeResetBetweenTestMethodsTest.java",
"subprojects/testng/src/test/java/org/mockitousage/testng/TestWithoutListenerShouldNotInitializeAnnotatedFieldsTest.java",
"subprojects/testng/src/test/java/org/mockitousage/testng/failuretests/TestNGShouldFailWhenMockitoListenerFailsTest.java",
"subprojects/testng/testng.gradle",
"test/org/mockito/AnnotationsAreCopiedFromMockedTypeTest.java",
"test/org/mockito/internal/configuration/MockInjectionTest.java",
"test/org/mockito/internal/creation/MockSettingsImplTest.java",
"test/org/mockito/internal/creation/bytebuddy/ByteBuddyMockMakerTest.java",
"test/org/mockito/internal/creation/bytebuddy/CachingMockBytecodeGeneratorTest.java",
"test/org/mockito/internal/debugging/VerboseMockInvocationLoggerTest.java",
"test/org/mockito/internal/handler/InvocationNotifierHandlerTest.java",
"test/org/mockito/internal/invocation/InvocationMatcherTest.java",
"test/org/mockito/internal/matchers/CapturingMatcherTest.java",
"test/org/mockito/internal/matchers/VarargCapturingMatcherTest.java",
"test/org/mockito/internal/progress/HandyReturnValuesTest.java",
"test/org/mockito/internal/stubbing/answers/AnswersValidatorTest.java",
"test/org/mockito/internal/stubbing/answers/ReturnsArgumentAtTest.java",
"test/org/mockito/internal/stubbing/defaultanswers/ReturnsGenericDeepStubsTest.java",
"test/org/mockito/internal/util/MockCreationValidatorTest.java",
"test/org/mockito/internal/util/MockUtilTest.java",
"test/org/mockito/internal/util/collections/HashCodeAndEqualsSafeSetTest.java",
"test/org/mockito/internal/util/junit/JUnitFailureHackerTest.java",
"test/org/mockito/internal/util/reflection/BeanPropertySetterTest.java",
"test/org/mockito/internal/util/reflection/FieldsTest.java",
"test/org/mockito/internal/util/reflection/GenericMetadataSupportTest.java",
"test/org/mockito/internal/util/reflection/ParameterizedConstructorInstantiatorTest.java",
"test/org/mockito/internal/util/reflection/SuperTypesLastSorterTest.java",
"test/org/mockito/internal/verification/NoMoreInteractionsTest.java",
"test/org/mockitousage/annotation/MockInjectionUsingConstructorIssue421Test.java",
"test/org/mockitousage/annotation/MockInjectionUsingConstructorTest.java",
"test/org/mockitousage/annotation/MockInjectionUsingSetterOrPropertyTest.java",
"test/org/mockitousage/annotation/SpyAnnotationTest.java",
"test/org/mockitousage/annotation/WrongSetOfAnnotationsTest.java",
"test/org/mockitousage/basicapi/MockingMultipleInterfacesTest.java",
"test/org/mockitousage/basicapi/MocksSerializationForAnnotationTest.java",
"test/org/mockitousage/basicapi/MocksSerializationTest.java",
"test/org/mockitousage/bugs/EqualsWithDeltaTest.java",
"test/org/mockitousage/bugs/IOOBExceptionShouldNotBeThrownWhenNotCodingFluentlyTest.java",
"test/org/mockitousage/bugs/ParentClassNotPublicTest.java",
"test/org/mockitousage/bugs/SpyShouldHaveNiceNameTest.java",
"test/org/mockitousage/bugs/creation/ShouldAllowInlineMockCreationTest.java",
"test/org/mockitousage/bugs/deepstubs/DeepStubsWronglyReportsSerializationProblemsTest.java",
"test/org/mockitousage/bugs/injection/Issue353InjectionMightNotHappenInCertainConfigurationTest.java",
"test/org/mockitousage/configuration/ClassCacheVersusClassReloadingTest.java",
"test/org/mockitousage/debugging/InvocationListenerCallbackTest.java",
"test/org/mockitousage/debugging/VerboseLoggingOfInvocationsOnMockTest.java",
"test/org/mockitousage/matchers/CapturingArgumentsTest.java",
"test/org/mockitousage/matchers/InvalidUseOfMatchersTest.java",
"test/org/mockitousage/misuse/SpyStubbingMisuseTest.java",
"test/org/mockitousage/serialization/DeepStubsSerializableTest.java",
"test/org/mockitousage/stubbing/DeepStubbingTest.java",
"test/org/mockitousage/stubbing/StubbingWithAdditionalAnswers.java",
"test/org/mockitousage/stubbing/StubbingWithDelegateTest.java",
"test/org/mockitoutil/ClassLoadersTest.java"
] | diff --git a/build.gradle b/build.gradle
index 635663b403..6bbc7b7efd 100644
--- a/build.gradle
+++ b/build.gradle
@@ -63,8 +63,7 @@ dependencies {
testCompile 'org.ow2.asm:asm:5.0.4'
- testCompile "org.easytesting:fest-assert:1.3"
- testCompile "org.easytesting:fest-util:1.1.4"
+ testCompile 'org.assertj:assertj-core:2.1.0'
testRuntime configurations.provided
| diff --git a/subprojects/testng/src/test/java/org/mockitousage/testng/AnnotatedFieldsShouldBeInitializedByMockitoTestNGListenerTest.java b/subprojects/testng/src/test/java/org/mockitousage/testng/AnnotatedFieldsShouldBeInitializedByMockitoTestNGListenerTest.java
index 06ad4c6ed9..640142a15a 100644
--- a/subprojects/testng/src/test/java/org/mockitousage/testng/AnnotatedFieldsShouldBeInitializedByMockitoTestNGListenerTest.java
+++ b/subprojects/testng/src/test/java/org/mockitousage/testng/AnnotatedFieldsShouldBeInitializedByMockitoTestNGListenerTest.java
@@ -12,7 +12,7 @@
import java.util.HashMap;
import java.util.List;
-import static org.fest.assertions.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThat;
@Listeners(MockitoTestNGListener.class)
public class AnnotatedFieldsShouldBeInitializedByMockitoTestNGListenerTest {
diff --git a/subprojects/testng/src/test/java/org/mockitousage/testng/CaptorAnnotatedFieldShouldBeClearedTest.java b/subprojects/testng/src/test/java/org/mockitousage/testng/CaptorAnnotatedFieldShouldBeClearedTest.java
index 4a1b2ad959..79c3071408 100644
--- a/subprojects/testng/src/test/java/org/mockitousage/testng/CaptorAnnotatedFieldShouldBeClearedTest.java
+++ b/subprojects/testng/src/test/java/org/mockitousage/testng/CaptorAnnotatedFieldShouldBeClearedTest.java
@@ -9,7 +9,7 @@
import java.util.List;
-import static org.fest.assertions.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
diff --git a/subprojects/testng/src/test/java/org/mockitousage/testng/ConfigurationMethodTest.java b/subprojects/testng/src/test/java/org/mockitousage/testng/ConfigurationMethodTest.java
index a268a9a364..76095f3af4 100644
--- a/subprojects/testng/src/test/java/org/mockitousage/testng/ConfigurationMethodTest.java
+++ b/subprojects/testng/src/test/java/org/mockitousage/testng/ConfigurationMethodTest.java
@@ -9,7 +9,7 @@
import java.io.IOException;
import java.util.Map;
-import static org.fest.assertions.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
@Listeners(MockitoTestNGListener.class)
diff --git a/subprojects/testng/src/test/java/org/mockitousage/testng/DontResetMocksIfNoListenerTest.java b/subprojects/testng/src/test/java/org/mockitousage/testng/DontResetMocksIfNoListenerTest.java
index b8075dcab4..5cbe4fc20d 100644
--- a/subprojects/testng/src/test/java/org/mockitousage/testng/DontResetMocksIfNoListenerTest.java
+++ b/subprojects/testng/src/test/java/org/mockitousage/testng/DontResetMocksIfNoListenerTest.java
@@ -8,7 +8,7 @@
import java.io.IOException;
import java.util.Map;
-import static org.fest.assertions.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
public class DontResetMocksIfNoListenerTest {
diff --git a/subprojects/testng/src/test/java/org/mockitousage/testng/EnsureMocksAreInitializedBeforeBeforeClassMethodTest.java b/subprojects/testng/src/test/java/org/mockitousage/testng/EnsureMocksAreInitializedBeforeBeforeClassMethodTest.java
index 49eaeacd3f..c26075825c 100644
--- a/subprojects/testng/src/test/java/org/mockitousage/testng/EnsureMocksAreInitializedBeforeBeforeClassMethodTest.java
+++ b/subprojects/testng/src/test/java/org/mockitousage/testng/EnsureMocksAreInitializedBeforeBeforeClassMethodTest.java
@@ -8,7 +8,7 @@
import java.util.Observer;
-import static org.fest.assertions.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThat;
@Listeners(MockitoTestNGListener.class)
public class EnsureMocksAreInitializedBeforeBeforeClassMethodTest {
diff --git a/subprojects/testng/src/test/java/org/mockitousage/testng/InitializeChildTestWhenParentHasListenerTest.java b/subprojects/testng/src/test/java/org/mockitousage/testng/InitializeChildTestWhenParentHasListenerTest.java
index c69118efa4..2a8cb70685 100644
--- a/subprojects/testng/src/test/java/org/mockitousage/testng/InitializeChildTestWhenParentHasListenerTest.java
+++ b/subprojects/testng/src/test/java/org/mockitousage/testng/InitializeChildTestWhenParentHasListenerTest.java
@@ -5,7 +5,7 @@
import java.util.Map;
-import static org.fest.assertions.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.testng.Assert.fail;
public class InitializeChildTestWhenParentHasListenerTest extends ParentTest {
diff --git a/subprojects/testng/src/test/java/org/mockitousage/testng/MockFieldsShouldBeResetBetweenTestMethodsTest.java b/subprojects/testng/src/test/java/org/mockitousage/testng/MockFieldsShouldBeResetBetweenTestMethodsTest.java
index ba3214fae2..f6c3933b9d 100644
--- a/subprojects/testng/src/test/java/org/mockitousage/testng/MockFieldsShouldBeResetBetweenTestMethodsTest.java
+++ b/subprojects/testng/src/test/java/org/mockitousage/testng/MockFieldsShouldBeResetBetweenTestMethodsTest.java
@@ -11,7 +11,7 @@
import java.util.List;
import java.util.Observable;
-import static org.fest.assertions.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.never;
diff --git a/subprojects/testng/src/test/java/org/mockitousage/testng/TestWithoutListenerShouldNotInitializeAnnotatedFieldsTest.java b/subprojects/testng/src/test/java/org/mockitousage/testng/TestWithoutListenerShouldNotInitializeAnnotatedFieldsTest.java
index 091a5d85a1..1133adfac9 100644
--- a/subprojects/testng/src/test/java/org/mockitousage/testng/TestWithoutListenerShouldNotInitializeAnnotatedFieldsTest.java
+++ b/subprojects/testng/src/test/java/org/mockitousage/testng/TestWithoutListenerShouldNotInitializeAnnotatedFieldsTest.java
@@ -10,7 +10,7 @@
import java.util.List;
import java.util.Map;
-import static org.fest.assertions.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThat;
public class TestWithoutListenerShouldNotInitializeAnnotatedFieldsTest {
diff --git a/subprojects/testng/src/test/java/org/mockitousage/testng/failuretests/TestNGShouldFailWhenMockitoListenerFailsTest.java b/subprojects/testng/src/test/java/org/mockitousage/testng/failuretests/TestNGShouldFailWhenMockitoListenerFailsTest.java
index 9720c94101..0870b9bb72 100644
--- a/subprojects/testng/src/test/java/org/mockitousage/testng/failuretests/TestNGShouldFailWhenMockitoListenerFailsTest.java
+++ b/subprojects/testng/src/test/java/org/mockitousage/testng/failuretests/TestNGShouldFailWhenMockitoListenerFailsTest.java
@@ -7,7 +7,7 @@
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;
-import static org.fest.assertions.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.testng.Assert.assertTrue;
@Test(
diff --git a/subprojects/testng/testng.gradle b/subprojects/testng/testng.gradle
index 1e6be98732..7b0fab9d6c 100644
--- a/subprojects/testng/testng.gradle
+++ b/subprojects/testng/testng.gradle
@@ -46,7 +46,7 @@ uploadArchives {
dependencies {
compile project.rootProject
compile 'org.testng:testng:6.3.1'
- testCompile 'org.easytesting:fest-assert:1.4'
+ testCompile 'org.assertj:assertj-core:2.1.0'
}
test {
diff --git a/test/org/mockito/AnnotationsAreCopiedFromMockedTypeTest.java b/test/org/mockito/AnnotationsAreCopiedFromMockedTypeTest.java
index 9635c9b103..09cdab4997 100644
--- a/test/org/mockito/AnnotationsAreCopiedFromMockedTypeTest.java
+++ b/test/org/mockito/AnnotationsAreCopiedFromMockedTypeTest.java
@@ -1,6 +1,6 @@
package org.mockito;
-import org.fest.assertions.Assertions;
+import org.assertj.core.api.Assertions;
import org.junit.Ignore;
import org.junit.Test;
diff --git a/test/org/mockito/internal/configuration/MockInjectionTest.java b/test/org/mockito/internal/configuration/MockInjectionTest.java
index fbb2f6e16f..32993ebd58 100644
--- a/test/org/mockito/internal/configuration/MockInjectionTest.java
+++ b/test/org/mockito/internal/configuration/MockInjectionTest.java
@@ -14,7 +14,7 @@
import java.util.Observer;
import java.util.Set;
-import static org.fest.assertions.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
@SuppressWarnings("unchecked")
diff --git a/test/org/mockito/internal/creation/MockSettingsImplTest.java b/test/org/mockito/internal/creation/MockSettingsImplTest.java
index 57fc5570a4..f67bcd78b3 100644
--- a/test/org/mockito/internal/creation/MockSettingsImplTest.java
+++ b/test/org/mockito/internal/creation/MockSettingsImplTest.java
@@ -4,7 +4,7 @@
*/
package org.mockito.internal.creation;
-import org.fest.assertions.Assertions;
+import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.exceptions.base.MockitoException;
diff --git a/test/org/mockito/internal/creation/bytebuddy/ByteBuddyMockMakerTest.java b/test/org/mockito/internal/creation/bytebuddy/ByteBuddyMockMakerTest.java
index e8578bccf0..8b55b7f650 100644
--- a/test/org/mockito/internal/creation/bytebuddy/ByteBuddyMockMakerTest.java
+++ b/test/org/mockito/internal/creation/bytebuddy/ByteBuddyMockMakerTest.java
@@ -18,7 +18,7 @@
import java.util.List;
-import static org.fest.assertions.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
import static org.mockitoutil.ClassLoaders.coverageTool;
diff --git a/test/org/mockito/internal/creation/bytebuddy/CachingMockBytecodeGeneratorTest.java b/test/org/mockito/internal/creation/bytebuddy/CachingMockBytecodeGeneratorTest.java
index cbbcfd840a..d66c152a2e 100644
--- a/test/org/mockito/internal/creation/bytebuddy/CachingMockBytecodeGeneratorTest.java
+++ b/test/org/mockito/internal/creation/bytebuddy/CachingMockBytecodeGeneratorTest.java
@@ -1,6 +1,6 @@
package org.mockito.internal.creation.bytebuddy;
-import static org.fest.assertions.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assume.assumeTrue;
import static org.mockito.internal.creation.bytebuddy.MockFeatures.withMockFeatures;
import static org.mockitoutil.ClassLoaders.inMemoryClassLoader;
diff --git a/test/org/mockito/internal/debugging/VerboseMockInvocationLoggerTest.java b/test/org/mockito/internal/debugging/VerboseMockInvocationLoggerTest.java
index 6bf40a5b5e..c5e3c913c0 100644
--- a/test/org/mockito/internal/debugging/VerboseMockInvocationLoggerTest.java
+++ b/test/org/mockito/internal/debugging/VerboseMockInvocationLoggerTest.java
@@ -16,7 +16,7 @@
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
-import static org.fest.assertions.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThat;
public class VerboseMockInvocationLoggerTest {
diff --git a/test/org/mockito/internal/handler/InvocationNotifierHandlerTest.java b/test/org/mockito/internal/handler/InvocationNotifierHandlerTest.java
index 5216f74168..1adb2a22cc 100644
--- a/test/org/mockito/internal/handler/InvocationNotifierHandlerTest.java
+++ b/test/org/mockito/internal/handler/InvocationNotifierHandlerTest.java
@@ -22,7 +22,7 @@
import java.text.ParseException;
import java.util.ArrayList;
-import static org.fest.assertions.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.willThrow;
diff --git a/test/org/mockito/internal/invocation/InvocationMatcherTest.java b/test/org/mockito/internal/invocation/InvocationMatcherTest.java
index 282bd8a1bf..a866f0fcbb 100644
--- a/test/org/mockito/internal/invocation/InvocationMatcherTest.java
+++ b/test/org/mockito/internal/invocation/InvocationMatcherTest.java
@@ -5,7 +5,7 @@
package org.mockito.internal.invocation;
-import org.fest.assertions.Assertions;
+import org.assertj.core.api.Assertions;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentMatcher;
diff --git a/test/org/mockito/internal/matchers/CapturingMatcherTest.java b/test/org/mockito/internal/matchers/CapturingMatcherTest.java
index b3bbbc76ce..783e03663e 100644
--- a/test/org/mockito/internal/matchers/CapturingMatcherTest.java
+++ b/test/org/mockito/internal/matchers/CapturingMatcherTest.java
@@ -4,7 +4,7 @@
*/
package org.mockito.internal.matchers;
-import org.fest.assertions.Assertions;
+import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.mockito.exceptions.base.MockitoException;
import org.mockitoutil.TestBase;
diff --git a/test/org/mockito/internal/matchers/VarargCapturingMatcherTest.java b/test/org/mockito/internal/matchers/VarargCapturingMatcherTest.java
index d6763fc0a3..6d517087a3 100644
--- a/test/org/mockito/internal/matchers/VarargCapturingMatcherTest.java
+++ b/test/org/mockito/internal/matchers/VarargCapturingMatcherTest.java
@@ -5,7 +5,7 @@
import org.mockito.exceptions.base.MockitoException;
import static java.util.Arrays.asList;
-import static org.fest.assertions.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
public class VarargCapturingMatcherTest {
diff --git a/test/org/mockito/internal/progress/HandyReturnValuesTest.java b/test/org/mockito/internal/progress/HandyReturnValuesTest.java
index f9ddd0e7e0..1894dea7a0 100644
--- a/test/org/mockito/internal/progress/HandyReturnValuesTest.java
+++ b/test/org/mockito/internal/progress/HandyReturnValuesTest.java
@@ -6,7 +6,7 @@
import org.junit.Test;
-import static org.fest.assertions.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
diff --git a/test/org/mockito/internal/stubbing/answers/AnswersValidatorTest.java b/test/org/mockito/internal/stubbing/answers/AnswersValidatorTest.java
index 9ec0d7ea6f..431c395a24 100644
--- a/test/org/mockito/internal/stubbing/answers/AnswersValidatorTest.java
+++ b/test/org/mockito/internal/stubbing/answers/AnswersValidatorTest.java
@@ -15,7 +15,7 @@
import java.nio.charset.CharacterCodingException;
import java.util.ArrayList;
-import static org.fest.assertions.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
diff --git a/test/org/mockito/internal/stubbing/answers/ReturnsArgumentAtTest.java b/test/org/mockito/internal/stubbing/answers/ReturnsArgumentAtTest.java
index 9977eb6fcb..44481ddc9c 100644
--- a/test/org/mockito/internal/stubbing/answers/ReturnsArgumentAtTest.java
+++ b/test/org/mockito/internal/stubbing/answers/ReturnsArgumentAtTest.java
@@ -4,7 +4,7 @@
*/
package org.mockito.internal.stubbing.answers;
-import static org.fest.assertions.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
import org.junit.Test;
import org.mockito.internal.invocation.InvocationBuilder;
diff --git a/test/org/mockito/internal/stubbing/defaultanswers/ReturnsGenericDeepStubsTest.java b/test/org/mockito/internal/stubbing/defaultanswers/ReturnsGenericDeepStubsTest.java
index a9422f8525..44066b8ced 100644
--- a/test/org/mockito/internal/stubbing/defaultanswers/ReturnsGenericDeepStubsTest.java
+++ b/test/org/mockito/internal/stubbing/defaultanswers/ReturnsGenericDeepStubsTest.java
@@ -11,7 +11,7 @@
import java.util.Map;
import java.util.Set;
-import static org.fest.assertions.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
diff --git a/test/org/mockito/internal/util/MockCreationValidatorTest.java b/test/org/mockito/internal/util/MockCreationValidatorTest.java
index 1cf6f8beb2..f911e4f7be 100644
--- a/test/org/mockito/internal/util/MockCreationValidatorTest.java
+++ b/test/org/mockito/internal/util/MockCreationValidatorTest.java
@@ -14,7 +14,7 @@
import java.util.Observer;
import static java.util.Arrays.asList;
-import static org.fest.assertions.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
@SuppressWarnings("unchecked")
diff --git a/test/org/mockito/internal/util/MockUtilTest.java b/test/org/mockito/internal/util/MockUtilTest.java
index 726804f9a6..43b0afd2fc 100644
--- a/test/org/mockito/internal/util/MockUtilTest.java
+++ b/test/org/mockito/internal/util/MockUtilTest.java
@@ -5,7 +5,7 @@
package org.mockito.internal.util;
-import org.fest.assertions.Assertions;
+import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.mockito.Mockito;
import org.mockito.exceptions.base.MockitoException;
diff --git a/test/org/mockito/internal/util/collections/HashCodeAndEqualsSafeSetTest.java b/test/org/mockito/internal/util/collections/HashCodeAndEqualsSafeSetTest.java
index 366595e15b..e8dc0c2688 100644
--- a/test/org/mockito/internal/util/collections/HashCodeAndEqualsSafeSetTest.java
+++ b/test/org/mockito/internal/util/collections/HashCodeAndEqualsSafeSetTest.java
@@ -10,7 +10,7 @@
import java.util.List;
import java.util.Observer;
-import static org.fest.assertions.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
public class HashCodeAndEqualsSafeSetTest {
diff --git a/test/org/mockito/internal/util/junit/JUnitFailureHackerTest.java b/test/org/mockito/internal/util/junit/JUnitFailureHackerTest.java
index 1409f07b22..5a0fbebc5c 100644
--- a/test/org/mockito/internal/util/junit/JUnitFailureHackerTest.java
+++ b/test/org/mockito/internal/util/junit/JUnitFailureHackerTest.java
@@ -4,7 +4,7 @@
*/
package org.mockito.internal.util.junit;
-import org.fest.assertions.Assertions;
+import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.junit.runner.Description;
import org.junit.runner.notification.Failure;
diff --git a/test/org/mockito/internal/util/reflection/BeanPropertySetterTest.java b/test/org/mockito/internal/util/reflection/BeanPropertySetterTest.java
index 9bd1a8d681..a0b6119a8b 100644
--- a/test/org/mockito/internal/util/reflection/BeanPropertySetterTest.java
+++ b/test/org/mockito/internal/util/reflection/BeanPropertySetterTest.java
@@ -4,7 +4,7 @@
*/
package org.mockito.internal.util.reflection;
-import org.fest.assertions.Assertions;
+import org.assertj.core.api.Assertions;
import org.junit.Test;
import java.io.File;
diff --git a/test/org/mockito/internal/util/reflection/FieldsTest.java b/test/org/mockito/internal/util/reflection/FieldsTest.java
index ef8409fc54..d86fb30370 100644
--- a/test/org/mockito/internal/util/reflection/FieldsTest.java
+++ b/test/org/mockito/internal/util/reflection/FieldsTest.java
@@ -8,7 +8,7 @@
import java.lang.reflect.Field;
-import static org.fest.assertions.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.internal.util.reflection.Fields.syntheticField;
public class FieldsTest {
diff --git a/test/org/mockito/internal/util/reflection/GenericMetadataSupportTest.java b/test/org/mockito/internal/util/reflection/GenericMetadataSupportTest.java
index 3beb894793..565e14bbda 100644
--- a/test/org/mockito/internal/util/reflection/GenericMetadataSupportTest.java
+++ b/test/org/mockito/internal/util/reflection/GenericMetadataSupportTest.java
@@ -4,7 +4,7 @@
*/
package org.mockito.internal.util.reflection;
-import static org.fest.assertions.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
import static org.mockito.internal.util.reflection.GenericMetadataSupport.inferFrom;
@@ -73,19 +73,19 @@ public void can_get_raw_type_from_ParameterizedType() throws Exception {
@Test
public void can_get_type_variables_from_Class() throws Exception {
- assertThat(inferFrom(GenericsNest.class).actualTypeArguments().keySet()).hasSize(1).onProperty("name").contains("K");
+ assertThat(inferFrom(GenericsNest.class).actualTypeArguments().keySet()).hasSize(1).extracting("name").contains("K");
assertThat(inferFrom(ListOfNumbers.class).actualTypeArguments().keySet()).isEmpty();
- assertThat(inferFrom(ListOfAnyNumbers.class).actualTypeArguments().keySet()).hasSize(1).onProperty("name").contains("N");
- assertThat(inferFrom(Map.class).actualTypeArguments().keySet()).hasSize(2).onProperty("name").contains("K", "V");
+ assertThat(inferFrom(ListOfAnyNumbers.class).actualTypeArguments().keySet()).hasSize(1).extracting("name").contains("N");
+ assertThat(inferFrom(Map.class).actualTypeArguments().keySet()).hasSize(2).extracting("name").contains("K", "V");
assertThat(inferFrom(Serializable.class).actualTypeArguments().keySet()).isEmpty();
assertThat(inferFrom(StringList.class).actualTypeArguments().keySet()).isEmpty();
}
@Test
public void can_get_type_variables_from_ParameterizedType() throws Exception {
- assertThat(inferFrom(GenericsNest.class.getGenericInterfaces()[0]).actualTypeArguments().keySet()).hasSize(2).onProperty("name").contains("K", "V");
- assertThat(inferFrom(ListOfAnyNumbers.class.getGenericInterfaces()[0]).actualTypeArguments().keySet()).hasSize(1).onProperty("name").contains("E");
- assertThat(inferFrom(Integer.class.getGenericInterfaces()[0]).actualTypeArguments().keySet()).hasSize(1).onProperty("name").contains("T");
+ assertThat(inferFrom(GenericsNest.class.getGenericInterfaces()[0]).actualTypeArguments().keySet()).hasSize(2).extracting("name").contains("K", "V");
+ assertThat(inferFrom(ListOfAnyNumbers.class.getGenericInterfaces()[0]).actualTypeArguments().keySet()).hasSize(1).extracting("name").contains("E");
+ assertThat(inferFrom(Integer.class.getGenericInterfaces()[0]).actualTypeArguments().keySet()).hasSize(1).extracting("name").contains("T");
assertThat(inferFrom(StringBuilder.class.getGenericInterfaces()[0]).actualTypeArguments().keySet()).isEmpty();
assertThat(inferFrom(StringList.class).actualTypeArguments().keySet()).isEmpty();
}
diff --git a/test/org/mockito/internal/util/reflection/ParameterizedConstructorInstantiatorTest.java b/test/org/mockito/internal/util/reflection/ParameterizedConstructorInstantiatorTest.java
index ada6a84113..2d234c0c5f 100644
--- a/test/org/mockito/internal/util/reflection/ParameterizedConstructorInstantiatorTest.java
+++ b/test/org/mockito/internal/util/reflection/ParameterizedConstructorInstantiatorTest.java
@@ -22,7 +22,7 @@
import java.util.Observer;
import java.util.Set;
-import static org.fest.assertions.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import static org.mockito.BDDMockito.given;
diff --git a/test/org/mockito/internal/util/reflection/SuperTypesLastSorterTest.java b/test/org/mockito/internal/util/reflection/SuperTypesLastSorterTest.java
index 4a635b7e7d..677a81a96a 100644
--- a/test/org/mockito/internal/util/reflection/SuperTypesLastSorterTest.java
+++ b/test/org/mockito/internal/util/reflection/SuperTypesLastSorterTest.java
@@ -5,7 +5,7 @@
import java.lang.reflect.Field;
import java.util.*;
-import static org.fest.assertions.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThat;
@SuppressWarnings("unused")
public class SuperTypesLastSorterTest {
diff --git a/test/org/mockito/internal/verification/NoMoreInteractionsTest.java b/test/org/mockito/internal/verification/NoMoreInteractionsTest.java
index ff87144842..725085b830 100644
--- a/test/org/mockito/internal/verification/NoMoreInteractionsTest.java
+++ b/test/org/mockito/internal/verification/NoMoreInteractionsTest.java
@@ -4,7 +4,7 @@
*/
package org.mockito.internal.verification;
-import org.fest.assertions.Assertions;
+import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.mockito.exceptions.verification.NoInteractionsWanted;
import org.mockito.exceptions.verification.VerificationInOrderFailure;
diff --git a/test/org/mockitousage/annotation/MockInjectionUsingConstructorIssue421Test.java b/test/org/mockitousage/annotation/MockInjectionUsingConstructorIssue421Test.java
index 1438ddf0b9..ba889814bd 100644
--- a/test/org/mockitousage/annotation/MockInjectionUsingConstructorIssue421Test.java
+++ b/test/org/mockitousage/annotation/MockInjectionUsingConstructorIssue421Test.java
@@ -5,7 +5,7 @@
package org.mockitousage.annotation;
-import static org.fest.assertions.Assertions.*;
+import static org.assertj.core.api.Assertions.*;
import org.junit.Test;
import org.junit.runner.RunWith;
diff --git a/test/org/mockitousage/annotation/MockInjectionUsingConstructorTest.java b/test/org/mockitousage/annotation/MockInjectionUsingConstructorTest.java
index 6a8857a547..816863a04a 100644
--- a/test/org/mockitousage/annotation/MockInjectionUsingConstructorTest.java
+++ b/test/org/mockitousage/annotation/MockInjectionUsingConstructorTest.java
@@ -24,7 +24,7 @@
import java.util.List;
import java.util.Set;
-import static org.fest.assertions.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
diff --git a/test/org/mockitousage/annotation/MockInjectionUsingSetterOrPropertyTest.java b/test/org/mockitousage/annotation/MockInjectionUsingSetterOrPropertyTest.java
index a530084da1..9b51e0b243 100644
--- a/test/org/mockitousage/annotation/MockInjectionUsingSetterOrPropertyTest.java
+++ b/test/org/mockitousage/annotation/MockInjectionUsingSetterOrPropertyTest.java
@@ -4,7 +4,7 @@
*/
package org.mockitousage.annotation;
-import org.fest.assertions.Assertions;
+import org.assertj.core.api.Assertions;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
diff --git a/test/org/mockitousage/annotation/SpyAnnotationTest.java b/test/org/mockitousage/annotation/SpyAnnotationTest.java
index b67f1365cd..77f6b5e3ed 100644
--- a/test/org/mockitousage/annotation/SpyAnnotationTest.java
+++ b/test/org/mockitousage/annotation/SpyAnnotationTest.java
@@ -13,7 +13,7 @@
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
-import org.fest.assertions.Assertions;
+import org.assertj.core.api.Assertions;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
diff --git a/test/org/mockitousage/annotation/WrongSetOfAnnotationsTest.java b/test/org/mockitousage/annotation/WrongSetOfAnnotationsTest.java
index 4f909dbc2f..8e6225d565 100644
--- a/test/org/mockitousage/annotation/WrongSetOfAnnotationsTest.java
+++ b/test/org/mockitousage/annotation/WrongSetOfAnnotationsTest.java
@@ -5,7 +5,7 @@
package org.mockitousage.annotation;
import java.util.List;
-import org.fest.assertions.Assertions;
+import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
diff --git a/test/org/mockitousage/basicapi/MockingMultipleInterfacesTest.java b/test/org/mockitousage/basicapi/MockingMultipleInterfacesTest.java
index de78ac8d55..a7517c605b 100644
--- a/test/org/mockitousage/basicapi/MockingMultipleInterfacesTest.java
+++ b/test/org/mockitousage/basicapi/MockingMultipleInterfacesTest.java
@@ -5,8 +5,8 @@
package org.mockitousage.basicapi;
-import static org.fest.assertions.Assertions.assertThat;
-import static org.fest.assertions.Fail.fail;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.withSettings;
import static org.mockitoutil.ClassLoaders.inMemoryClassLoader;
diff --git a/test/org/mockitousage/basicapi/MocksSerializationForAnnotationTest.java b/test/org/mockitousage/basicapi/MocksSerializationForAnnotationTest.java
index 214c7c0a47..e0016e5ee6 100644
--- a/test/org/mockitousage/basicapi/MocksSerializationForAnnotationTest.java
+++ b/test/org/mockitousage/basicapi/MocksSerializationForAnnotationTest.java
@@ -24,7 +24,7 @@
import java.util.Collections;
import java.util.List;
import java.util.Observable;
-import org.fest.assertions.Assertions;
+import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.mockito.InOrder;
import org.mockito.Mock;
diff --git a/test/org/mockitousage/basicapi/MocksSerializationTest.java b/test/org/mockitousage/basicapi/MocksSerializationTest.java
index 90056c61ed..79f36ea387 100644
--- a/test/org/mockitousage/basicapi/MocksSerializationTest.java
+++ b/test/org/mockitousage/basicapi/MocksSerializationTest.java
@@ -26,7 +26,7 @@
import java.util.Collections;
import java.util.List;
import java.util.Observable;
-import org.fest.assertions.Assertions;
+import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.mockito.InOrder;
import org.mockito.Mockito;
diff --git a/test/org/mockitousage/bugs/EqualsWithDeltaTest.java b/test/org/mockitousage/bugs/EqualsWithDeltaTest.java
index da6d9281ff..582a6a1ece 100644
--- a/test/org/mockitousage/bugs/EqualsWithDeltaTest.java
+++ b/test/org/mockitousage/bugs/EqualsWithDeltaTest.java
@@ -4,7 +4,7 @@
import org.mockito.ArgumentMatcher;
import org.mockito.internal.matchers.EqualsWithDelta;
-import static org.fest.assertions.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThat;
public class EqualsWithDeltaTest {
diff --git a/test/org/mockitousage/bugs/IOOBExceptionShouldNotBeThrownWhenNotCodingFluentlyTest.java b/test/org/mockitousage/bugs/IOOBExceptionShouldNotBeThrownWhenNotCodingFluentlyTest.java
index c66291d4c3..e462276863 100644
--- a/test/org/mockitousage/bugs/IOOBExceptionShouldNotBeThrownWhenNotCodingFluentlyTest.java
+++ b/test/org/mockitousage/bugs/IOOBExceptionShouldNotBeThrownWhenNotCodingFluentlyTest.java
@@ -10,7 +10,7 @@
import java.util.Map;
-import static org.fest.assertions.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
diff --git a/test/org/mockitousage/bugs/ParentClassNotPublicTest.java b/test/org/mockitousage/bugs/ParentClassNotPublicTest.java
index 961b150ec1..8b6c0f78e2 100644
--- a/test/org/mockitousage/bugs/ParentClassNotPublicTest.java
+++ b/test/org/mockitousage/bugs/ParentClassNotPublicTest.java
@@ -4,7 +4,7 @@
*/
package org.mockitousage.bugs;
-import org.fest.assertions.Assertions;
+import org.assertj.core.api.Assertions;
import org.junit.Assume;
import org.junit.Before;
import org.junit.Test;
diff --git a/test/org/mockitousage/bugs/SpyShouldHaveNiceNameTest.java b/test/org/mockitousage/bugs/SpyShouldHaveNiceNameTest.java
index 6e297efce7..82b6241dc5 100644
--- a/test/org/mockitousage/bugs/SpyShouldHaveNiceNameTest.java
+++ b/test/org/mockitousage/bugs/SpyShouldHaveNiceNameTest.java
@@ -5,7 +5,7 @@
package org.mockitousage.bugs;
-import org.fest.assertions.Assertions;
+import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.mockito.Spy;
import org.mockitoutil.TestBase;
diff --git a/test/org/mockitousage/bugs/creation/ShouldAllowInlineMockCreationTest.java b/test/org/mockitousage/bugs/creation/ShouldAllowInlineMockCreationTest.java
index 3751a89047..568ef18ad4 100644
--- a/test/org/mockitousage/bugs/creation/ShouldAllowInlineMockCreationTest.java
+++ b/test/org/mockitousage/bugs/creation/ShouldAllowInlineMockCreationTest.java
@@ -5,7 +5,7 @@
package org.mockitousage.bugs.creation;
-import org.fest.assertions.Assertions;
+import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Spy;
diff --git a/test/org/mockitousage/bugs/deepstubs/DeepStubsWronglyReportsSerializationProblemsTest.java b/test/org/mockitousage/bugs/deepstubs/DeepStubsWronglyReportsSerializationProblemsTest.java
index 6344fab10c..8c20f80d92 100644
--- a/test/org/mockitousage/bugs/deepstubs/DeepStubsWronglyReportsSerializationProblemsTest.java
+++ b/test/org/mockitousage/bugs/deepstubs/DeepStubsWronglyReportsSerializationProblemsTest.java
@@ -2,7 +2,7 @@
import org.junit.Test;
-import static org.fest.assertions.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
diff --git a/test/org/mockitousage/bugs/injection/Issue353InjectionMightNotHappenInCertainConfigurationTest.java b/test/org/mockitousage/bugs/injection/Issue353InjectionMightNotHappenInCertainConfigurationTest.java
index 26b075ea1c..f6acc8a375 100644
--- a/test/org/mockitousage/bugs/injection/Issue353InjectionMightNotHappenInCertainConfigurationTest.java
+++ b/test/org/mockitousage/bugs/injection/Issue353InjectionMightNotHappenInCertainConfigurationTest.java
@@ -10,7 +10,7 @@
import java.util.HashMap;
import java.util.Map;
-import static org.fest.assertions.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertSame;
@RunWith(MockitoJUnitRunner.class)
diff --git a/test/org/mockitousage/configuration/ClassCacheVersusClassReloadingTest.java b/test/org/mockitousage/configuration/ClassCacheVersusClassReloadingTest.java
index 9193b95b2f..25d8604230 100644
--- a/test/org/mockitousage/configuration/ClassCacheVersusClassReloadingTest.java
+++ b/test/org/mockitousage/configuration/ClassCacheVersusClassReloadingTest.java
@@ -5,11 +5,11 @@
package org.mockitousage.configuration;
-import static org.fest.assertions.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import java.util.concurrent.Callable;
-import org.fest.assertions.Condition;
+import org.assertj.core.api.Condition;
import org.junit.Assume;
import org.junit.Test;
import org.mockito.exceptions.base.MockitoException;
@@ -38,8 +38,8 @@ public void should_throw_ClassCastException_on_second_call() throws Exception {
.containsIgnoringCase("objenesis")
.containsIgnoringCase("MockitoConfiguration");
assertThat(e.getCause())
- .satisfies(thatCceIsThrownFrom("java.lang.Class.cast"))
- .satisfies(thatCceIsThrownFrom("org.mockito.internal.creation.cglib.ClassImposterizer.imposterise"));
+ .has(cceIsThrownFrom("java.lang.Class.cast"))
+ .has(cceIsThrownFrom("org.mockito.internal.creation.cglib.ClassImposterizer.imposterise"));
}
}
@@ -51,7 +51,7 @@ public void should_not_throw_ClassCastException_when_objenesis_cache_disabled()
doInNewChildRealm(testMethodClassLoaderRealm, "org.mockitousage.configuration.ClassCacheVersusClassReloadingTest$DoTheMocking");
}
- private Condition<Throwable> thatCceIsThrownFrom(final String stacktraceElementDescription) {
+ private Condition<Throwable> cceIsThrownFrom(final String stacktraceElementDescription) {
return new Condition<Throwable>() {
@Override
public boolean matches(Throwable throwable) {
diff --git a/test/org/mockitousage/debugging/InvocationListenerCallbackTest.java b/test/org/mockitousage/debugging/InvocationListenerCallbackTest.java
index 040b06c3a8..56828dd4a8 100644
--- a/test/org/mockitousage/debugging/InvocationListenerCallbackTest.java
+++ b/test/org/mockitousage/debugging/InvocationListenerCallbackTest.java
@@ -10,7 +10,7 @@
import org.mockito.listeners.InvocationListener;
import org.mockito.listeners.MethodInvocationReport;
-import static org.fest.assertions.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.willReturn;
diff --git a/test/org/mockitousage/debugging/VerboseLoggingOfInvocationsOnMockTest.java b/test/org/mockitousage/debugging/VerboseLoggingOfInvocationsOnMockTest.java
index 588e62abb3..3dbaa0ffea 100644
--- a/test/org/mockitousage/debugging/VerboseLoggingOfInvocationsOnMockTest.java
+++ b/test/org/mockitousage/debugging/VerboseLoggingOfInvocationsOnMockTest.java
@@ -12,7 +12,7 @@
import static org.mockito.Mockito.withSettings;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
-import org.fest.assertions.Assertions;
+import org.assertj.core.api.Assertions;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
diff --git a/test/org/mockitousage/matchers/CapturingArgumentsTest.java b/test/org/mockitousage/matchers/CapturingArgumentsTest.java
index 379075d414..43c362a9b4 100644
--- a/test/org/mockitousage/matchers/CapturingArgumentsTest.java
+++ b/test/org/mockitousage/matchers/CapturingArgumentsTest.java
@@ -5,7 +5,7 @@
package org.mockitousage.matchers;
-import org.fest.assertions.Assertions;
+import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.exceptions.base.MockitoException;
diff --git a/test/org/mockitousage/matchers/InvalidUseOfMatchersTest.java b/test/org/mockitousage/matchers/InvalidUseOfMatchersTest.java
index 7b12324806..756c9d0388 100644
--- a/test/org/mockitousage/matchers/InvalidUseOfMatchersTest.java
+++ b/test/org/mockitousage/matchers/InvalidUseOfMatchersTest.java
@@ -14,7 +14,7 @@
import org.mockito.runners.MockitoJUnitRunner;
import org.mockitousage.IMethods;
-import static org.fest.assertions.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.when;
diff --git a/test/org/mockitousage/misuse/SpyStubbingMisuseTest.java b/test/org/mockitousage/misuse/SpyStubbingMisuseTest.java
index 7d9cabdae0..77179ad292 100644
--- a/test/org/mockitousage/misuse/SpyStubbingMisuseTest.java
+++ b/test/org/mockitousage/misuse/SpyStubbingMisuseTest.java
@@ -8,7 +8,7 @@
import org.mockito.exceptions.misusing.WrongTypeOfReturnValue;
import static org.junit.Assert.fail;
-import static org.fest.assertions.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.*;
public class SpyStubbingMisuseTest {
diff --git a/test/org/mockitousage/serialization/DeepStubsSerializableTest.java b/test/org/mockitousage/serialization/DeepStubsSerializableTest.java
index 800a58e2e1..bdd5cee862 100644
--- a/test/org/mockitousage/serialization/DeepStubsSerializableTest.java
+++ b/test/org/mockitousage/serialization/DeepStubsSerializableTest.java
@@ -1,6 +1,6 @@
package org.mockitousage.serialization;
-import static org.fest.assertions.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
diff --git a/test/org/mockitousage/stubbing/DeepStubbingTest.java b/test/org/mockitousage/stubbing/DeepStubbingTest.java
index be8bcaa33b..77fbdd28c3 100644
--- a/test/org/mockitousage/stubbing/DeepStubbingTest.java
+++ b/test/org/mockitousage/stubbing/DeepStubbingTest.java
@@ -22,7 +22,7 @@
import java.net.Socket;
import java.util.Locale;
import javax.net.SocketFactory;
-import org.fest.assertions.Assertions;
+import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.mockito.InOrder;
import org.mockito.exceptions.verification.TooManyActualInvocations;
diff --git a/test/org/mockitousage/stubbing/StubbingWithAdditionalAnswers.java b/test/org/mockitousage/stubbing/StubbingWithAdditionalAnswers.java
index 3f428ad24a..0ba0430e3c 100644
--- a/test/org/mockitousage/stubbing/StubbingWithAdditionalAnswers.java
+++ b/test/org/mockitousage/stubbing/StubbingWithAdditionalAnswers.java
@@ -10,7 +10,7 @@
import org.mockito.runners.MockitoJUnitRunner;
import org.mockitousage.IMethods;
-import static org.fest.assertions.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.AdditionalAnswers.returnsArgAt;
import static org.mockito.AdditionalAnswers.returnsFirstArg;
import static org.mockito.AdditionalAnswers.returnsLastArg;
diff --git a/test/org/mockitousage/stubbing/StubbingWithDelegateTest.java b/test/org/mockitousage/stubbing/StubbingWithDelegateTest.java
index bc4494a473..e8fc92ab43 100644
--- a/test/org/mockitousage/stubbing/StubbingWithDelegateTest.java
+++ b/test/org/mockitousage/stubbing/StubbingWithDelegateTest.java
@@ -4,7 +4,7 @@
*/
package org.mockitousage.stubbing;
-import static org.fest.assertions.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
import static org.mockito.AdditionalAnswers.delegatesTo;
import static org.mockito.Mockito.doReturn;
diff --git a/test/org/mockitoutil/ClassLoadersTest.java b/test/org/mockitoutil/ClassLoadersTest.java
index 1f6b0900bd..557ecfe446 100644
--- a/test/org/mockitoutil/ClassLoadersTest.java
+++ b/test/org/mockitoutil/ClassLoadersTest.java
@@ -3,7 +3,7 @@
import org.junit.Test;
import org.mockito.Mockito;
-import static org.fest.assertions.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
import static org.mockitoutil.ClassLoaders.currentClassLoader;
import static org.mockitoutil.ClassLoaders.excludingClassLoader;
| test | train | 2015-07-08T16:31:14 | "2015-07-08T15:20:18Z" | szpak | train |
mockito/mockito/260_261 | mockito/mockito | mockito/mockito/260 | mockito/mockito/261 | [
"timestamp(timedelta=2.0, similarity=0.9121201880561255)"
] | 817b04b82ee802f0cf9009952521d1d7496c69d7 | 298330658c63b36a154470f742e829bdf713c921 | [] | [] | "2015-07-11T14:36:16Z" | [] | Typo in documentation | Very minor thing, there's an extra "at" (@) in the documentation.
If you go to http://site.mockito.org/mockito/docs/current/org/mockito/Mockito.html#33
![image](https://cloud.githubusercontent.com/assets/338917/8634099/6c7f5264-27b8-11e5-93d9-98b725c9f749.png)
| [
"src/main/java/org/mockito/Mockito.java"
] | [
"src/main/java/org/mockito/Mockito.java"
] | [] | diff --git a/src/main/java/org/mockito/Mockito.java b/src/main/java/org/mockito/Mockito.java
index 1e833596a2..72e4b28c08 100644
--- a/src/main/java/org/mockito/Mockito.java
+++ b/src/main/java/org/mockito/Mockito.java
@@ -1051,7 +1051,7 @@
* such as <code>@{@link Mock}</code>, <code>@{@link Spy}</code>, <code>@{@link InjectMocks}</code>, etc.
*
* <ul>
- * <li>Annotating the JUnit test class with a <code>@{@link org.junit.runner.RunWith}(@{@link MockitoJUnitRunner}.class)</code></li>
+ * <li>Annotating the JUnit test class with a <code>@{@link org.junit.runner.RunWith}({@link MockitoJUnitRunner}.class)</code></li>
* <li>Invoking <code>{@link MockitoAnnotations#initMocks(Object)}</code> in the <code>@{@link org.junit.Before}</code> method</li>
* </ul>
*
| null | train | train | 2015-07-10T21:03:51 | "2015-07-11T14:34:41Z" | carlos-aguayo | train |
mockito/mockito/243_280 | mockito/mockito | mockito/mockito/243 | mockito/mockito/280 | [
"keyword_pr_to_issue",
"timestamp(timedelta=0.0, similarity=0.9144901177873329)"
] | 2f88f06d6b0e851ff8ed2125085d3faac3f4ee1b | 27e074066ecec55ed086f7430246ef1c8818819f | [
"thanks for reporting this one !\n",
"ByteBuddyMockMaker.getHandler(Object mock) method checks for null using instanceof operator\n`if (!(mock instanceof MockAccess)) {\n return null;\n}`\n\nI presume it is not a bug. \n",
"> I presume it is not a bug.\n\nNope\n",
"How about we document the change in the behavior. Javadoc ok?\n\nOn Sun, Jul 19, 2015 at 11:28 PM, Brice Dutheil notifications@github.com\nwrote:\n\n> I presume it is not a bug.\n> \n> Nope\n> \n> —\n> Reply to this email directly or view it on GitHub\n> https://github.com/mockito/mockito/issues/243#issuecomment-122708060.\n\n## \n\nSzczepan Faber\nFounder mockito.org; Core dev gradle.org\ntweets as @szczepiq; blogs at blog.mockito.org\n",
"`MockUtil` is an internal class, I don't think we have to document that one. But I believe we should fix the code there.\n",
"The public API (or, SPI) is MockMaker.getHandler(Object mock).\n\nThe current JavaDoc doesn't mention whether null could be passed in. Although in v1.9.5 it was guaranteed that nulls won't be passed in.\n\nIf v1.10.19 drops that guarantee, Android's [DexMakerMockMaker](https://android.googlesource.com/platform/external/dexmaker/+/34f760b98a72000325cc83c88f41de011471432e/src/mockito/java/com/google/dexmaker/mockito/DexmakerMockMaker.java) is broken because it doesn't make the effort to check for null.\n\nI personally think it's pointless for Mockito to ever call MockMaker.getHandler(null) because nothing but null would seem reasonable to be returned anyway, so why risk the NPE?\n\nBut if this change in the implicit contract needs to happen, the document change is at MockMaker.getHandler(). Something like \"null could be passed in and implementations should return null in that case\" would be clear enough.\n",
"yes agreed with @fluentfuture \n",
"While working on #277, I fixed the null-check in the MockScanner (as tests were failing if you would remove this check). The check can be [found here](https://github.com/mockito/mockito/pull/277/files#diff-5f69ba708be52e3b8f1216aff3582f4aR34)\n"
] | [] | "2015-08-06T11:39:38Z" | [
"bug"
] | MockUtil.isMock() no longer checks null | In version 1.9.5, MockUtil.isMock() is defined as:
```
return instance != null && isMockitoMock(instance);
```
In v1.10.19 and HEAD, the `instance != null` check is gone.
This method is called by MockScanner when injecting mock instances on fields, where field values can be null.
Is this a bug? Or it's up to MockMaker.getHandler() to check for null?
If it's a bug, I can fix it. But then we'll need to wait for v2.0 before upgrading Mockito for the company's code base.
If it's up to the mock maker, then I guess we need to fix Google's DexmakerMockMaker to add a line of `if (mock == null) return null;`
| [
"src/main/java/org/mockito/internal/util/MockUtil.java"
] | [
"src/main/java/org/mockito/internal/util/MockUtil.java"
] | [] | diff --git a/src/main/java/org/mockito/internal/util/MockUtil.java b/src/main/java/org/mockito/internal/util/MockUtil.java
index 96b47a73bf..3ea20cded9 100644
--- a/src/main/java/org/mockito/internal/util/MockUtil.java
+++ b/src/main/java/org/mockito/internal/util/MockUtil.java
@@ -70,7 +70,7 @@ public boolean isSpy(Object mock) {
}
private <T> boolean isMockitoMock(T mock) {
- return mockMaker.getHandler(mock) != null;
+ return mock != null && mockMaker.getHandler(mock) != null;
}
public MockName getMockName(Object mock) {
| null | test | train | 2015-07-28T13:00:51 | "2015-06-26T18:57:40Z" | fluentfuture | train |
mockito/mockito/183_286 | mockito/mockito | mockito/mockito/183 | mockito/mockito/286 | [
"keyword_pr_to_issue",
"timestamp(timedelta=0.0, similarity=0.8811629453447426)"
] | 971be4d8184ec916a5ebc2395050804da22b5b33 | 318d92fe4effc1ff23c62b4909538307239b7e7c | [
"Hi, in your use case could you be interested to stubbing only i.e. not interested by verifications ?\n\nIn this case there's this setting may prove useful : `withSettings().stubOnly()`\n",
"No, that would not solve my problem.\n\nMy current issue is that I have a large number of permutations (x \\* y) of input data, and the plan was to create reusable methods for one of the \"dimensions\" (`x_case1()`, `x_case2()`, `x_case3()`, ...) and then from each test case of the other dimensions (`@Test y_case1()`) call the methods of the first dimension **and pass a mock as a parameter**. That way I can set up the stubbing once, for the Y dimension, and then test and `verify()` the different X scenarios with that stub.\n\nThe workaround in this case could be to pass a lambda that does the stubbing, after each scenario has created it's mock.\n\n(I do agree it would be preferable in this particular case to refactor this to something that is more testable, and hopefully I can get part of the way there, but sometimes reality is just complex and it is definitely not the first time I've missed this particular feature in Mockito.)\n",
"OK\n\nWell at the moment the team is clearly busy in other RL projects. If you manage to make a nice PR (see the contributing guide) of this feature before we do work on it, which seems most probable we may integrate your work :)\n",
"I created a new issue (#284) for removing any invocations which have been verified. In my optioning resetting the invocations would then not been needed anymore and the current reset can stay as-is. This also give you a stronger guarantee that you're really verifying all invocations of the mock.\n"
] | [
"I like the notion of _clearing_, I propose the pull this word up to the `Mockito` class facade. instead of using 3 different words (reset, clear, remove).\n"
] | "2015-08-22T22:19:30Z" | [
"enhancement"
] | Feature request: Method to reset mock interactions/invocations without resetting stubs | I'm still missing the ability to reset the invocations on a mock, while keeping all the stubbing, so this is a GitHub equivalent of https://code.google.com/p/mockito/issues/detail?id=316
Some background discussion exists in a [thread](https://groups.google.com/forum/#!topic/mockito/5G-XnpIhP3s) that also refers to [issue 84](https://code.google.com/p/mockito/issues/detail?id=84) for which there already [is a GitHub issue](https://github.com/mockito/mockito/issues/86).
| [
"src/main/java/org/mockito/Mockito.java",
"src/main/java/org/mockito/internal/MockitoCore.java",
"src/main/java/org/mockito/internal/stubbing/InvocationContainer.java",
"src/main/java/org/mockito/internal/stubbing/InvocationContainerImpl.java",
"src/main/java/org/mockito/internal/verification/DefaultRegisteredInvocations.java",
"src/main/java/org/mockito/internal/verification/RegisteredInvocations.java",
"src/main/java/org/mockito/internal/verification/SingleRegisteredInvocation.java"
] | [
"src/main/java/org/mockito/Mockito.java",
"src/main/java/org/mockito/internal/MockitoCore.java",
"src/main/java/org/mockito/internal/stubbing/InvocationContainer.java",
"src/main/java/org/mockito/internal/stubbing/InvocationContainerImpl.java",
"src/main/java/org/mockito/internal/verification/DefaultRegisteredInvocations.java",
"src/main/java/org/mockito/internal/verification/RegisteredInvocations.java",
"src/main/java/org/mockito/internal/verification/SingleRegisteredInvocation.java"
] | [
"src/test/java/org/mockitousage/basicapi/ResetInvocationsTest.java"
] | diff --git a/src/main/java/org/mockito/Mockito.java b/src/main/java/org/mockito/Mockito.java
index 25db83abee..302bd6cce6 100644
--- a/src/main/java/org/mockito/Mockito.java
+++ b/src/main/java/org/mockito/Mockito.java
@@ -1703,6 +1703,21 @@ public static <T> void reset(T ... mocks) {
MOCKITO_CORE.reset(mocks);
}
+ /**
+ * Use this method in order to only clear invocations, when stubbing is non-trivial. Use-cases can be:
+ * <ul>
+ * <li>You are using a dependency injection framework to inject your mocks.</li>
+ * <li>The mock is used in a stateful scenario. For example a class is Singleton which depends on your mock.</li>
+ * </ul>
+ *
+ * <b>Try to avoid this method at all costs. Only clear invocations if you are unable to efficiently test your program.</b>
+ * @param <T> The type of the mocks
+ * @param mocks The mocks to clear the invocations for
+ */
+ public static <T> void clearInvocations(T ... mocks) {
+ MOCKITO_CORE.clearInvocations(mocks);
+ }
+
/**
* Checks if any of given mocks has any unverified interaction.
* <p>
diff --git a/src/main/java/org/mockito/internal/MockitoCore.java b/src/main/java/org/mockito/internal/MockitoCore.java
index 8ad222f849..e6dcb469bc 100644
--- a/src/main/java/org/mockito/internal/MockitoCore.java
+++ b/src/main/java/org/mockito/internal/MockitoCore.java
@@ -95,6 +95,16 @@ public <T> void reset(T ... mocks) {
mockUtil.resetMock(m);
}
}
+
+ public <T> void clearInvocations(T ... mocks) {
+ mockingProgress.validateState();
+ mockingProgress.reset();
+ mockingProgress.resetOngoingStubbing();
+
+ for (T m : mocks) {
+ mockUtil.getMockHandler(m).getInvocationContainer().clearInvocations();
+ }
+ }
public void verifyNoMoreInteractions(Object... mocks) {
assertMocksNotEmpty(mocks);
@@ -182,4 +192,5 @@ public Object[] ignoreStubs(Object... mocks) {
public MockingDetails mockingDetails(Object toInspect) {
return new DefaultMockingDetails(toInspect, new MockUtil());
}
+
}
diff --git a/src/main/java/org/mockito/internal/stubbing/InvocationContainer.java b/src/main/java/org/mockito/internal/stubbing/InvocationContainer.java
index 0e82e85cb9..b926183f63 100644
--- a/src/main/java/org/mockito/internal/stubbing/InvocationContainer.java
+++ b/src/main/java/org/mockito/internal/stubbing/InvocationContainer.java
@@ -12,5 +12,7 @@
public interface InvocationContainer {
List<Invocation> getInvocations();
+ void clearInvocations();
+
List<StubbedInvocationMatcher> getStubbedInvocations();
}
diff --git a/src/main/java/org/mockito/internal/stubbing/InvocationContainerImpl.java b/src/main/java/org/mockito/internal/stubbing/InvocationContainerImpl.java
index 9d10ab9bce..fb391e3cef 100644
--- a/src/main/java/org/mockito/internal/stubbing/InvocationContainerImpl.java
+++ b/src/main/java/org/mockito/internal/stubbing/InvocationContainerImpl.java
@@ -121,6 +121,10 @@ public List<Invocation> getInvocations() {
return registeredInvocations.getAll();
}
+ public void clearInvocations() {
+ registeredInvocations.clear();
+ }
+
public List<StubbedInvocationMatcher> getStubbedInvocations() {
return stubbed;
}
diff --git a/src/main/java/org/mockito/internal/verification/DefaultRegisteredInvocations.java b/src/main/java/org/mockito/internal/verification/DefaultRegisteredInvocations.java
index a9690066a2..7b6442bdd2 100644
--- a/src/main/java/org/mockito/internal/verification/DefaultRegisteredInvocations.java
+++ b/src/main/java/org/mockito/internal/verification/DefaultRegisteredInvocations.java
@@ -44,6 +44,12 @@ public List<Invocation> getAll() {
return ListUtil.filter(copiedList, new RemoveToString());
}
+ public void clear() {
+ synchronized (invocations) {
+ invocations.clear();
+ }
+ }
+
public boolean isEmpty() {
synchronized (invocations) {
return invocations.isEmpty();
diff --git a/src/main/java/org/mockito/internal/verification/RegisteredInvocations.java b/src/main/java/org/mockito/internal/verification/RegisteredInvocations.java
index 1cb2131775..75c0b3f224 100644
--- a/src/main/java/org/mockito/internal/verification/RegisteredInvocations.java
+++ b/src/main/java/org/mockito/internal/verification/RegisteredInvocations.java
@@ -21,6 +21,8 @@ public interface RegisteredInvocations {
List<Invocation> getAll();
+ void clear();
+
boolean isEmpty();
}
diff --git a/src/main/java/org/mockito/internal/verification/SingleRegisteredInvocation.java b/src/main/java/org/mockito/internal/verification/SingleRegisteredInvocation.java
index 07da74c378..67ceafa52e 100644
--- a/src/main/java/org/mockito/internal/verification/SingleRegisteredInvocation.java
+++ b/src/main/java/org/mockito/internal/verification/SingleRegisteredInvocation.java
@@ -27,6 +27,10 @@ public List<Invocation> getAll() {
return Collections.emptyList();
}
+ public void clear() {
+ invocation = null;
+ }
+
public boolean isEmpty() {
return invocation == null;
}
| diff --git a/src/test/java/org/mockitousage/basicapi/ResetInvocationsTest.java b/src/test/java/org/mockitousage/basicapi/ResetInvocationsTest.java
new file mode 100644
index 0000000000..3f18478086
--- /dev/null
+++ b/src/test/java/org/mockitousage/basicapi/ResetInvocationsTest.java
@@ -0,0 +1,48 @@
+package org.mockitousage.basicapi;
+
+import org.junit.Test;
+import org.mockito.Mock;
+import org.mockito.exceptions.misusing.NotAMockException;
+import org.mockitousage.IMethods;
+import org.mockitoutil.TestBase;
+
+import static org.mockito.Mockito.*;
+
+public class ResetInvocationsTest extends TestBase {
+
+ @Mock IMethods methods;
+ @Mock IMethods moarMethods;
+
+ @Test
+ public void reset_invocations_should_reset_only_invocations() {
+ when(methods.simpleMethod()).thenReturn("return");
+
+ methods.simpleMethod();
+ verify(methods).simpleMethod();
+
+ clearInvocations(methods);
+
+ verifyNoMoreInteractions(methods);
+ assertEquals("return", methods.simpleMethod());
+ }
+
+ @Test
+ public void should_reset_invocations_on_multiple_mocks() {
+ methods.simpleMethod();
+ moarMethods.simpleMethod();
+
+ clearInvocations(methods, moarMethods);
+
+ verifyNoMoreInteractions(methods, moarMethods);
+ }
+
+ @Test(expected = NotAMockException.class)
+ public void resettingNonMockIsSafe() {
+ clearInvocations("");
+ }
+
+ @Test(expected = NotAMockException.class)
+ public void resettingNullIsSafe() {
+ clearInvocations(new Object[]{null});
+ }
+}
| test | train | 2015-12-08T12:52:28 | "2015-03-19T19:16:34Z" | mjiderhamn | train |
mockito/mockito/124_287 | mockito/mockito | mockito/mockito/124 | mockito/mockito/287 | [
"keyword_pr_to_issue"
] | 495406554354a23980ac40fb991c1dae8f4105aa | 08b0daeea01e17a63b0c817ff3139ab918aec710 | [
"As a possible example of the way to handle it, maybe it could be modeled after the same way that AssertJ added deferred composite assertion handling through [their own JUnit @Rule](http://joel-costigliola.github.io/assertj/assertj-core-features-highlight.html#soft-assertions):\n"
] | [
"I think this rule should be instantiated this way (Also the method should only expose an interface for example `VerificationCollector`) :\n\n``` java\n@Rule VerificationCollector collector = MockitoJUnit.collector();\n```\n",
"Since it is JUnit specific, this whole PR should live within the package `org.mockito.junit`, we'd like to move runners as well under this package too.\n",
"Don't do these hacks ;)\nInstead play with core JUnit functionality like `JUnitCore`, there's some example in the test code base (like `org.mockitousage.bugs.MockitoRunnerBreaksWhenNoTestMethodsTest`)\n",
"I honestly didn't have a clue how to fix this and internet wasn't helpful either. I will check out the test you mentioned!\n",
"No problem ;)\n",
"I don't think this class needs to be public anymore ;)\n"
] | "2015-08-23T14:42:07Z" | [] | Concise way to collect multiple verify failures, ideally with JUnitCollector or derivative | If you are using more than one verify statement as test post-conditions, it would be nice to be able to collect each failure and continue with the remaining verify statements or asserts that follow. JUnit provides the ErrorCollector @Rule to facilitate this kid of thing, but the current [ErrorCollector API](http://junit.org/apidocs/org/junit/rules/ErrorCollector.html) requires either
- a Matcher<T> and a value to compare
- or a Callable<Object>
The Mockito verify statements only return void, however, since they depend on throwing exceptions. I have not thought of an ideal, non-disruptive way to use JUnit's ErrorCollector to aggregate multiple Mockito verify failure
| [
"src/main/java/org/mockito/junit/MockitoJUnit.java"
] | [
"src/main/java/org/mockito/junit/MockitoJUnit.java",
"src/main/java/org/mockito/junit/VerificationCollector.java",
"src/main/java/org/mockito/junit/VerificationCollectorImpl.java"
] | [
"src/test/java/org/mockitousage/junitrule/VerificationCollectorImplTest.java"
] | diff --git a/src/main/java/org/mockito/junit/MockitoJUnit.java b/src/main/java/org/mockito/junit/MockitoJUnit.java
index f13b667796..b680079e80 100644
--- a/src/main/java/org/mockito/junit/MockitoJUnit.java
+++ b/src/main/java/org/mockito/junit/MockitoJUnit.java
@@ -16,4 +16,14 @@ public class MockitoJUnit {
public static MockitoRule rule() {
return new MockitoJUnitRule();
}
+
+ /**
+ * Creates a rule instance that can perform lazy verifications.
+ *
+ * @see VerificationCollector
+ * @return the rule instance
+ */
+ public static VerificationCollector collector() {
+ return new VerificationCollectorImpl();
+ }
}
diff --git a/src/main/java/org/mockito/junit/VerificationCollector.java b/src/main/java/org/mockito/junit/VerificationCollector.java
new file mode 100644
index 0000000000..432dc55b36
--- /dev/null
+++ b/src/main/java/org/mockito/junit/VerificationCollector.java
@@ -0,0 +1,62 @@
+package org.mockito.junit;
+
+import org.junit.rules.TestRule;
+import org.mockito.exceptions.base.MockitoAssertionError;
+import org.mockito.verification.VerificationMode;
+
+/**
+ * Use this rule in order to collect multiple verification failures and report at once.
+ *
+ * In the example below, the verification failure thrown by {@code byteReturningMethod()} does not block
+ * verifying against the {@code simpleMethod()}. After the test is run, a report is generated stating all
+ * collect verification failures.
+ *
+ * <pre class="code"><code class="java">
+ * @Rule
+ * public VerificationCollector collector = MockitoJUnit.collector();
+ *
+ * @Test
+ * public void should_fail() {
+ * IMethods methods = mock(IMethods.class);
+ *
+ * collector.verify(methods).byteReturningMethod();
+ * collector.verify(methods).simpleMethod();
+ * }
+ * </code></pre>
+ *
+ * @see org.mockito.Mockito#verify(Object)
+ * @see org.mockito.Mockito#verify(Object, VerificationMode)
+ */
+public interface VerificationCollector extends TestRule {
+
+ /**
+ * Lazily verify certain behaviour happened once.
+ *
+ * @see org.mockito.Mockito#verify(Object)
+ *
+ * @param <T> The type of the mock
+ * @param mock to be verified
+ * @return mock object itself
+ */
+ <T> T verify(T mock);
+
+ /**
+ * Lazily verify certain behaviour happened at least once / exact number of times / never.
+ *
+ * @see org.mockito.Mockito#verify(Object, VerificationMode)
+ *
+ * @param mock to be verified
+ * @param mode times(x), atLeastOnce() or never()
+ * @param <T> The type of the mock
+ * @return mock object itself
+ */
+ <T> T verify(T mock, VerificationMode mode);
+
+ /**
+ * Collect all lazily verified behaviour. If there were failed verifications, it will
+ * throw a MockitoAssertionError containing all messages indicating the failed verifications.
+ *
+ * @throws MockitoAssertionError If there were failed verifications
+ */
+ void collectAndReport() throws MockitoAssertionError;
+}
diff --git a/src/main/java/org/mockito/junit/VerificationCollectorImpl.java b/src/main/java/org/mockito/junit/VerificationCollectorImpl.java
new file mode 100644
index 0000000000..64b7ec2697
--- /dev/null
+++ b/src/main/java/org/mockito/junit/VerificationCollectorImpl.java
@@ -0,0 +1,89 @@
+package org.mockito.junit;
+
+import org.junit.rules.TestRule;
+import org.junit.runner.Description;
+import org.junit.runners.model.Statement;
+import org.mockito.exceptions.base.MockitoAssertionError;
+import org.mockito.internal.MockitoCore;
+import org.mockito.internal.verification.api.VerificationData;
+import org.mockito.verification.VerificationMode;
+
+import static org.mockito.Mockito.times;
+
+/**
+ * Mockito implementation of VerificationCollector.
+ */
+class VerificationCollectorImpl implements VerificationCollector {
+
+ private static final MockitoCore MOCKITO_CORE = new MockitoCore();
+
+ private StringBuilder builder;
+ private int numberOfFailures;
+
+ public VerificationCollectorImpl() {
+ this.resetBuilder();
+ }
+
+ public Statement apply(final Statement base, final Description description) {
+ return new Statement() {
+ @Override
+ public void evaluate() throws Throwable {
+ base.evaluate();
+ VerificationCollectorImpl.this.collectAndReport();
+ }
+ };
+ }
+
+ public <T> T verify(T mock) {
+ return MOCKITO_CORE.verify(mock, new VerificationWrapper(times(1)));
+ }
+
+ public <T> T verify(T mock, VerificationMode mode) {
+ return MOCKITO_CORE.verify(mock, new VerificationWrapper(mode));
+ }
+
+ public void collectAndReport() throws MockitoAssertionError {
+ if (this.numberOfFailures > 0) {
+ String error = this.builder.toString();
+
+ this.resetBuilder();
+
+ throw new MockitoAssertionError(error);
+ }
+ }
+
+ private void resetBuilder() {
+ this.builder = new StringBuilder()
+ .append("There were multiple verification failures:");
+ this.numberOfFailures = 0;
+ }
+
+ private void append(String message) {
+ this.numberOfFailures++;
+ this.builder.append('\n')
+ .append(this.numberOfFailures).append(". ")
+ .append(message.substring(1, message.length()));
+ }
+
+ private class VerificationWrapper implements VerificationMode {
+
+ private final VerificationMode delegate;
+
+ private VerificationWrapper(VerificationMode delegate) {
+ this.delegate = delegate;
+ }
+
+ public void verify(VerificationData data) {
+ try {
+ this.delegate.verify(data);
+ } catch (MockitoAssertionError error) {
+ VerificationCollectorImpl.this.append(error.getMessage());
+ }
+ }
+
+ public VerificationMode description(String description) {
+ throw new IllegalStateException("Should not fail in this mode");
+ }
+ }
+
+}
| diff --git a/src/test/java/org/mockitousage/junitrule/VerificationCollectorImplTest.java b/src/test/java/org/mockitousage/junitrule/VerificationCollectorImplTest.java
new file mode 100644
index 0000000000..4749304fee
--- /dev/null
+++ b/src/test/java/org/mockitousage/junitrule/VerificationCollectorImplTest.java
@@ -0,0 +1,121 @@
+package org.mockitousage.junitrule;
+
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.runner.JUnitCore;
+import org.junit.runner.Result;
+import org.mockito.exceptions.base.MockitoAssertionError;
+import org.mockito.junit.MockitoJUnit;
+import org.mockito.junit.VerificationCollector;
+import org.mockitousage.IMethods;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.Assert.fail;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+
+public class VerificationCollectorImplTest {
+
+ @Test
+ public void should_not_throw_any_exceptions_when_verifications_are_succesful() {
+ VerificationCollector collector = MockitoJUnit.collector();
+
+ IMethods methods = mock(IMethods.class);
+ methods.simpleMethod();
+
+ collector.verify(methods).simpleMethod();
+ collector.collectAndReport();
+ }
+
+ @Test(expected = MockitoAssertionError.class)
+ public void should_collect_verification_failures() {
+ VerificationCollector collector = MockitoJUnit.collector();
+
+ IMethods methods = mock(IMethods.class);
+
+ collector.verify(methods).simpleMethod();
+ collector.collectAndReport();
+ }
+
+ @Test
+ public void should_collect_multiple_verification_failures() {
+ VerificationCollector collector = MockitoJUnit.collector();
+
+ IMethods methods = mock(IMethods.class);
+
+ collector.verify(methods).simpleMethod();
+ collector.verify(methods).byteReturningMethod();
+ try {
+ collector.collectAndReport();
+ fail();
+ } catch (MockitoAssertionError error) {
+ assertThat(error).hasMessageContaining("1. Wanted but not invoked:");
+ assertThat(error).hasMessageContaining("2. Wanted but not invoked:");
+ }
+ }
+
+ @Test
+ public void should_only_collect_failures_ignore_succesful_verifications() {
+ VerificationCollector collector = MockitoJUnit.collector();
+
+ IMethods methods = mock(IMethods.class);
+
+ collector.verify(methods, never()).simpleMethod();
+ collector.verify(methods).byteReturningMethod();
+
+ this.assertAtLeastOneFailure(collector);
+ }
+
+ @Test
+ public void should_continue_collecting_after_failing_verification() {
+ VerificationCollector collector = MockitoJUnit.collector();
+
+ IMethods methods = mock(IMethods.class);
+ methods.simpleMethod();
+
+ collector.verify(methods).byteReturningMethod();
+ collector.verify(methods).simpleMethod();
+
+ this.assertAtLeastOneFailure(collector);
+ }
+
+ private void assertAtLeastOneFailure(VerificationCollector collector) {
+ try {
+ collector.collectAndReport();
+ fail();
+ } catch (MockitoAssertionError error) {
+ assertThat(error).hasMessageContaining("1. Wanted but not invoked:");
+ assertThat(error.getMessage()).doesNotContain("2.");
+ }
+ }
+
+ @Test
+ public void should_invoke_collector_rule_after_test() {
+ JUnitCore runner = new JUnitCore();
+ Result result = runner.run(VerificationCollectorRuleInner.class);
+
+ assertThat(result.getFailureCount()).isEqualTo(1);
+ assertThat(result.getFailures().get(0).getMessage()).contains("1. Wanted but not invoked:");
+ }
+
+ public static class VerificationCollectorRuleInner {
+
+ @Rule
+ public VerificationCollector collector = MockitoJUnit.collector();
+
+ @Test
+ public void should_fail() {
+ IMethods methods = mock(IMethods.class);
+
+ collector.verify(methods).simpleMethod();
+ }
+
+ @Test
+ public void should_not_fail() {
+ IMethods methods = mock(IMethods.class);
+ methods.simpleMethod();
+
+ collector.verify(methods).simpleMethod();
+ }
+ }
+}
| train | train | 2015-11-26T18:56:50 | "2014-11-25T17:28:12Z" | welkman | train |
mockito/mockito/273_294 | mockito/mockito | mockito/mockito/273 | mockito/mockito/294 | [
"keyword_issue_to_pr",
"timestamp(timedelta=67.0, similarity=0.8910939217609104)"
] | a821f7b0ec47f3214bf6f0361df5deb211fa2214 | 39e732869eef5d6b54af4a6890b895fba430171d | [
"Fixed by #294\n"
] | [] | "2015-09-21T18:29:41Z" | [
"1.* incompatible"
] | Get rid of ReturnValues | `org.mockito.ReturnValues` has been deprecated for years, it should be removed in mockito 2.0
| [
"src/main/java/org/mockito/Mockito.java",
"src/main/java/org/mockito/ReturnValues.java",
"src/main/java/org/mockito/configuration/DefaultMockitoConfiguration.java",
"src/main/java/org/mockito/configuration/IMockitoConfiguration.java",
"src/main/java/org/mockito/internal/configuration/GlobalConfiguration.java",
"src/main/java/org/mockito/internal/stubbing/answers/AnswerReturnValuesAdapter.java",
"src/main/java/org/mockito/internal/stubbing/defaultanswers/ForwardsInvocations.java",
"src/main/java/org/mockito/internal/stubbing/defaultanswers/package.html"
] | [
"src/main/java/org/mockito/Mockito.java",
"src/main/java/org/mockito/configuration/DefaultMockitoConfiguration.java",
"src/main/java/org/mockito/configuration/IMockitoConfiguration.java",
"src/main/java/org/mockito/internal/configuration/GlobalConfiguration.java",
"src/main/java/org/mockito/internal/stubbing/defaultanswers/ForwardsInvocations.java",
"src/main/java/org/mockito/internal/stubbing/defaultanswers/package.html"
] | [] | diff --git a/src/main/java/org/mockito/Mockito.java b/src/main/java/org/mockito/Mockito.java
index 04f4a9e69e..e2eca63a6d 100644
--- a/src/main/java/org/mockito/Mockito.java
+++ b/src/main/java/org/mockito/Mockito.java
@@ -1327,41 +1327,6 @@ public static MockingDetails mockingDetails(Object toInspect) {
return MOCKITO_CORE.mockingDetails(toInspect);
}
- /**
- * <b>Deprecated : Please use mock(Foo.class, defaultAnswer);</b>
- * <p>
- * See {@link Mockito#mock(Class, Answer)}
- * <p>
- * Why it is deprecated? ReturnValues is being replaced by Answer
- * for better consistency & interoperability of the framework.
- * Answer interface has been in Mockito for a while and it has the same responsibility as ReturnValues.
- * There's no point in mainting exactly the same interfaces.
- * <p>
- * Creates mock with a specified strategy for its return values.
- * It's quite advanced feature and typically you don't need it to write decent tests.
- * However it can be helpful when working with legacy systems.
- * <p>
- * Obviously return values are used only when you don't stub the method call.
- *
- * <pre class="code"><code class="java">
- * Foo mock = mock(Foo.class, Mockito.RETURNS_SMART_NULLS);
- * Foo mockTwo = mock(Foo.class, new YourOwnReturnValues());
- * </code></pre>
- *
- * <p>See examples in javadoc for {@link Mockito} class</p>
- *
- * @param classToMock class or interface to mock
- * @param returnValues default return values for unstubbed methods
- *
- * @return mock object
- *
- * @deprecated <b>Please use mock(Foo.class, defaultAnswer);</b>
- */
- @Deprecated
- public static <T> T mock(Class<T> classToMock, ReturnValues returnValues) {
- return mock(classToMock, withSettings().defaultAnswer(new AnswerReturnValuesAdapter(returnValues)));
- }
-
/**
* Creates mock with a specified strategy for its answers to interactions.
* It's quite advanced feature and typically you don't need it to write decent tests.
diff --git a/src/main/java/org/mockito/ReturnValues.java b/src/main/java/org/mockito/ReturnValues.java
deleted file mode 100644
index f9402129c2..0000000000
--- a/src/main/java/org/mockito/ReturnValues.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * Copyright (c) 2007 Mockito contributors
- * This program is made available under the terms of the MIT License.
- */
-
-package org.mockito;
-
-import org.mockito.invocation.InvocationOnMock;
-import org.mockito.stubbing.Answer;
-
-/**
- * @deprecated
- * <b>Instead, please use {@link Answer} interface</b>
- * <p>
- * In rare cases your code might not compile with recent deprecation & changes.
- * Very sorry for inconvenience but it had to be done in order to keep framework consistent.
- * <p>
- * Why it is deprecated? ReturnValues is being replaced by Answer
- * for better consistency & interoperability of the framework.
- * Answer interface has been in Mockito for a while and it has the same responsibility as ReturnValues.
- * There's no point in mainting exactly the same interfaces.
- * <p>
- * Configures return values for an unstubbed invocation
- * <p>
- * Can be used in {@link Mockito#mock(Class, ReturnValues)}
- */
-@Deprecated
-public interface ReturnValues {
-
- /**
- * return value for an unstubbed invocation
- *
- * @param invocation placeholder for mock and a method
- * @return the return value
- */
- Object valueFor(InvocationOnMock invocation) throws Throwable;
-}
\ No newline at end of file
diff --git a/src/main/java/org/mockito/configuration/DefaultMockitoConfiguration.java b/src/main/java/org/mockito/configuration/DefaultMockitoConfiguration.java
index fe9a8f6062..ce5714d0c0 100644
--- a/src/main/java/org/mockito/configuration/DefaultMockitoConfiguration.java
+++ b/src/main/java/org/mockito/configuration/DefaultMockitoConfiguration.java
@@ -4,7 +4,6 @@
*/
package org.mockito.configuration;
-import org.mockito.ReturnValues;
import org.mockito.internal.configuration.InjectingAnnotationEngine;
import org.mockito.internal.stubbing.defaultanswers.ReturnsEmptyValues;
import org.mockito.stubbing.Answer;
@@ -16,17 +15,7 @@
* <p>
* See javadocs for {@link IMockitoConfiguration} on info how to configure Mockito
*/
-@SuppressWarnings("deprecation")//suppressed until ReturnValues are removed
public class DefaultMockitoConfiguration implements IMockitoConfiguration {
-
- /* (non-Javadoc)
- * @see org.mockito.IMockitoConfiguration#getReturnValues()
- */
- @Deprecated
- public ReturnValues getReturnValues() {
- throw new RuntimeException("\n" + "This method should not be used by the framework because it was deprecated"
- + "\n" + "Please report the failure to the Mockito mailing list");
- }
public Answer<Object> getDefaultAnswer() {
return new ReturnsEmptyValues();
diff --git a/src/main/java/org/mockito/configuration/IMockitoConfiguration.java b/src/main/java/org/mockito/configuration/IMockitoConfiguration.java
index 2f693879ff..cebd25f366 100644
--- a/src/main/java/org/mockito/configuration/IMockitoConfiguration.java
+++ b/src/main/java/org/mockito/configuration/IMockitoConfiguration.java
@@ -4,7 +4,6 @@
*/
package org.mockito.configuration;
-import org.mockito.ReturnValues;
import org.mockito.internal.stubbing.defaultanswers.ReturnsEmptyValues;
import org.mockito.stubbing.Answer;
@@ -26,31 +25,8 @@
* <p>
* If you have comments on Mockito configuration feature don't hesitate to write to mockito@googlegroups.com
*/
-@SuppressWarnings("deprecation")//suppressed until ReturnValues are removed
public interface IMockitoConfiguration {
- /**
- * @deprecated
- * <b>Please use {@link IMockitoConfiguration#getDefaultAnswer()}</b>
- * <p>
- * Steps:
- * <p>
- * 1. Leave the implementation of getReturnValues() method empty - it's not going to be used anyway.
- * <p>
- * 2. Implement getDefaultAnswer() instead.
- * <p>
- * In rare cases your code might not compile with recent deprecation & changes.
- * Very sorry for inconvenience but it had to be done in order to keep framework consistent.
- * <p>
- * See javadoc {@link ReturnValues} for info why this method was deprecated
- * <p>
- * Allows configuring the default return values of unstubbed invocations
- * <p>
- * See javadoc for {@link IMockitoConfiguration}
- */
- @Deprecated
- ReturnValues getReturnValues();
-
/**
* Allows configuring the default answers of unstubbed invocations
* <p>
diff --git a/src/main/java/org/mockito/internal/configuration/GlobalConfiguration.java b/src/main/java/org/mockito/internal/configuration/GlobalConfiguration.java
index 9a54c27a69..c8a94e8937 100644
--- a/src/main/java/org/mockito/internal/configuration/GlobalConfiguration.java
+++ b/src/main/java/org/mockito/internal/configuration/GlobalConfiguration.java
@@ -4,7 +4,6 @@
*/
package org.mockito.internal.configuration;
-import org.mockito.ReturnValues;
import org.mockito.configuration.AnnotationEngine;
import org.mockito.configuration.DefaultMockitoConfiguration;
import org.mockito.configuration.IMockitoConfiguration;
@@ -15,7 +14,6 @@
/**
* Thread-safe wrapper on user-defined org.mockito.configuration.MockitoConfiguration implementation
*/
-@SuppressWarnings("deprecation")//suppressed until ReturnValues are removed
public class GlobalConfiguration implements IMockitoConfiguration, Serializable {
private static final long serialVersionUID = -2860353062105505938L;
@@ -47,10 +45,6 @@ public static void validate() {
new GlobalConfiguration();
}
- public ReturnValues getReturnValues() {
- return GLOBAL_CONFIGURATION.get().getReturnValues();
- }
-
public AnnotationEngine getAnnotationEngine() {
return GLOBAL_CONFIGURATION.get().getAnnotationEngine();
}
diff --git a/src/main/java/org/mockito/internal/stubbing/answers/AnswerReturnValuesAdapter.java b/src/main/java/org/mockito/internal/stubbing/answers/AnswerReturnValuesAdapter.java
deleted file mode 100644
index 1d5492ed31..0000000000
--- a/src/main/java/org/mockito/internal/stubbing/answers/AnswerReturnValuesAdapter.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * Copyright (c) 2007 Mockito contributors
- * This program is made available under the terms of the MIT License.
- */
-package org.mockito.internal.stubbing.answers;
-
-import java.io.Serializable;
-
-import org.mockito.ReturnValues;
-import org.mockito.invocation.InvocationOnMock;
-import org.mockito.stubbing.Answer;
-
-//It's ok to suppress deprecation because this class goes away as soon as ReturnValues disappears in future release
-@SuppressWarnings("deprecation")
-public class AnswerReturnValuesAdapter implements Answer<Object>, Serializable {
-
- private static final long serialVersionUID = 1418158596876713469L;
- private final ReturnValues returnValues;
-
- public AnswerReturnValuesAdapter(ReturnValues returnValues) {
- this.returnValues = returnValues;
- }
-
- public Object answer(InvocationOnMock invocation) throws Throwable {
- return returnValues.valueFor(invocation);
- }
-}
\ No newline at end of file
diff --git a/src/main/java/org/mockito/internal/stubbing/defaultanswers/ForwardsInvocations.java b/src/main/java/org/mockito/internal/stubbing/defaultanswers/ForwardsInvocations.java
index df86442619..1916a62ce2 100644
--- a/src/main/java/org/mockito/internal/stubbing/defaultanswers/ForwardsInvocations.java
+++ b/src/main/java/org/mockito/internal/stubbing/defaultanswers/ForwardsInvocations.java
@@ -9,9 +9,6 @@
import java.lang.reflect.Method;
import org.mockito.exceptions.Reporter;
-import org.mockito.exceptions.base.MockitoException;
-import org.mockito.internal.stubbing.answers.MethodInfo;
-import org.mockito.internal.util.Primitives;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
diff --git a/src/main/java/org/mockito/internal/stubbing/defaultanswers/package.html b/src/main/java/org/mockito/internal/stubbing/defaultanswers/package.html
index 15877151bd..f2dee90a8c 100644
--- a/src/main/java/org/mockito/internal/stubbing/defaultanswers/package.html
+++ b/src/main/java/org/mockito/internal/stubbing/defaultanswers/package.html
@@ -4,5 +4,5 @@
-->
<body>
-Implementations of ReturnValues
+Implementations of Answer
</body>
\ No newline at end of file
| null | train | train | 2015-08-11T14:53:30 | "2015-07-27T14:20:16Z" | bric3 | train |
mockito/mockito/311_314 | mockito/mockito | mockito/mockito/311 | mockito/mockito/314 | [
"timestamp(timedelta=0.0, similarity=0.8877391757752712)",
"keyword_pr_to_issue"
] | e8640baba7eeaf4d333696492b6868feb115094f | 7bd8cb501439886a31d787cc708d0c77101a3fde | [] | [] | "2015-10-31T16:46:56Z" | [
"BDD"
] | Add BDD version of verifyNoMoreInteractions() | Current state:
``` java
then(file).should().moveTo(directory);
verifyNoMoreInteractions(file);
```
Would be great to have BDD replacement for `verifyNoMoreInteractions()`. Then the test would be even nicer:
``` java
then(file).should().moveTo(directory);
then(file).shouldHaveNoMoreInteractions();
```
If you agree, I will submit a PR.
| [
"src/main/java/org/mockito/BDDMockito.java"
] | [
"src/main/java/org/mockito/BDDMockito.java"
] | [
"src/test/java/org/mockitousage/customization/BDDMockitoTest.java"
] | diff --git a/src/main/java/org/mockito/BDDMockito.java b/src/main/java/org/mockito/BDDMockito.java
index 560cdf8bd7..7bb8f4679f 100644
--- a/src/main/java/org/mockito/BDDMockito.java
+++ b/src/main/java/org/mockito/BDDMockito.java
@@ -57,6 +57,7 @@
* person.ride(bike);
*
* then(person).should(times(2)).ride(bike);
+ * then(person).shouldHaveNoMoreInteractions();
* then(police).shouldHaveZeroInteractions();
* </code></pre>
* <p>
@@ -256,6 +257,12 @@ public interface Then<T> {
* @since 2.0
*/
void shouldHaveZeroInteractions();
+
+ /**
+ * @see #verifyNoMoreInteractions(Object...)
+ * @since 2.0
+ */
+ void shouldHaveNoMoreInteractions();
}
/**
@@ -309,6 +316,14 @@ public T should(InOrder inOrder, VerificationMode mode) {
public void shouldHaveZeroInteractions() {
verifyZeroInteractions(mock);
}
+
+ /**
+ * @see #verifyNoMoreInteractions(Object...)
+ * @since 2.0
+ */
+ public void shouldHaveNoMoreInteractions() {
+ verifyNoMoreInteractions(mock);
+ }
}
/**
| diff --git a/src/test/java/org/mockitousage/customization/BDDMockitoTest.java b/src/test/java/org/mockitousage/customization/BDDMockitoTest.java
index c207361c9d..b74487ef04 100644
--- a/src/test/java/org/mockitousage/customization/BDDMockitoTest.java
+++ b/src/test/java/org/mockitousage/customization/BDDMockitoTest.java
@@ -246,6 +246,7 @@ public void should_pass_for_expected_behavior_that_happened() {
mock.booleanObjectReturningMethod();
then(mock).should().booleanObjectReturningMethod();
+ then(mock).shouldHaveNoMoreInteractions();
}
@Test
@@ -263,6 +264,18 @@ public void should_fail_when_mock_had_unwanted_interactions() {
} catch (NoInteractionsWanted expected) { }
}
+ @Test
+ public void should_fail_when_mock_had_more_interactions_than_expected() {
+ mock.booleanObjectReturningMethod();
+ mock.byteObjectReturningMethod();
+
+ then(mock).should().booleanObjectReturningMethod();
+ try {
+ then(mock).shouldHaveNoMoreInteractions();
+ fail("should have reported that no more interactions were wanted");
+ } catch (NoInteractionsWanted expected) { }
+ }
+
@Test
public void should_pass_for_interactions_that_happened_in_correct_order() {
mock.booleanObjectReturningMethod();
| train | train | 2015-10-21T22:46:49 | "2015-10-29T22:05:44Z" | mkordas | train |
mockito/mockito/316_317 | mockito/mockito | mockito/mockito/316 | mockito/mockito/317 | [
"timestamp(timedelta=0.0, similarity=0.9396315082112713)",
"keyword_pr_to_issue"
] | 971be4d8184ec916a5ebc2395050804da22b5b33 | 8017ee1ff766b96725a64d0a2fff79e26300a19b | [] | [] | "2015-11-10T12:21:38Z" | [
"enhancement"
] | modify StackTraceFilter to not strip away "good" elements from the middle | according to javadoc of org.mockito.internal.exceptions.stacktrace.StackTraceFilter, filter works like this:
[a+, b+, c-, d+, e+, f-, g+] -> [a+, b+, g+]
it would be better to not strip away "good" d and e elements:
[a+, b+, c-, d+, e+, f-, g+] -> [a+, b+, d+, e+, g+]
What do you think about this? For me current behaviour is very inconvenient, I had to turn it off.
| [
"src/main/java/org/mockito/internal/exceptions/stacktrace/StackTraceFilter.java"
] | [
"src/main/java/org/mockito/internal/exceptions/stacktrace/StackTraceFilter.java"
] | [
"src/test/java/org/mockito/internal/exceptions/stacktrace/StackTraceFilterTest.java"
] | diff --git a/src/main/java/org/mockito/internal/exceptions/stacktrace/StackTraceFilter.java b/src/main/java/org/mockito/internal/exceptions/stacktrace/StackTraceFilter.java
index cd462dcee1..2b5bb658cc 100644
--- a/src/main/java/org/mockito/internal/exceptions/stacktrace/StackTraceFilter.java
+++ b/src/main/java/org/mockito/internal/exceptions/stacktrace/StackTraceFilter.java
@@ -10,8 +10,6 @@
import java.io.Serializable;
import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.LinkedList;
import java.util.List;
public class StackTraceFilter implements Serializable {
@@ -20,38 +18,22 @@ public class StackTraceFilter implements Serializable {
private static final StackTraceCleaner CLEANER =
Plugins.getStackTraceCleanerProvider().getStackTraceCleaner(new DefaultStackTraceCleaner());
-
+
/**
* Example how the filter works (+/- means good/bad):
- * [a+, b+, c-, d+, e+, f-, g+] -> [a+, b+, g+]
- * Basically removes all bad from the middle. If any good are in the middle of bad those are also removed.
+ * [a+, b+, c-, d+, e+, f-, g+] -> [a+, b+, d+, e+, g+]
+ * Basically removes all bad from the middle.
+ * <strike>If any good are in the middle of bad those are also removed.</strike>
*/
public StackTraceElement[] filter(StackTraceElement[] target, boolean keepTop) {
//TODO: profile
- List<StackTraceElement> unfilteredStackTrace = Arrays.asList(target);
-
- int lastBad = -1;
- int firstBad = -1;
- for (int i = 0; i < unfilteredStackTrace.size(); i++) {
- if (!CLEANER.isOut(unfilteredStackTrace.get(i))) {
- continue;
- }
- lastBad = i;
- if (firstBad == -1) {
- firstBad = i;
+ final List<StackTraceElement> filtered = new ArrayList<StackTraceElement>();
+ for (StackTraceElement aTarget : target) {
+ if (!CLEANER.isOut(aTarget)) {
+ filtered.add(aTarget);
}
}
-
- List<StackTraceElement> top;
- if (keepTop && firstBad != -1) {
- top = unfilteredStackTrace.subList(0, firstBad);
- } else {
- top = new LinkedList<StackTraceElement>();
- }
-
- List<StackTraceElement> bottom = unfilteredStackTrace.subList(lastBad + 1, unfilteredStackTrace.size());
- List<StackTraceElement> filtered = new ArrayList<StackTraceElement>(top);
- filtered.addAll(bottom);
- return filtered.toArray(new StackTraceElement[]{});
+ StackTraceElement[] result = new StackTraceElement[filtered.size()];
+ return filtered.toArray(result);
}
}
\ No newline at end of file
| diff --git a/src/test/java/org/mockito/internal/exceptions/stacktrace/StackTraceFilterTest.java b/src/test/java/org/mockito/internal/exceptions/stacktrace/StackTraceFilterTest.java
index 3d4185e7c9..0b1e588d86 100644
--- a/src/test/java/org/mockito/internal/exceptions/stacktrace/StackTraceFilterTest.java
+++ b/src/test/java/org/mockito/internal/exceptions/stacktrace/StackTraceFilterTest.java
@@ -40,7 +40,7 @@ public void shouldFilterOutMockitoPackage() {
}
@Test
- public void shouldFilterOutTracesMiddleBadTraces() {
+ public void shouldNotFilterOutTracesMiddleGoodTraces() {
StackTraceElement[] t = new TraceBuilder().classes(
"org.test.MockitoSampleTest",
"org.test.TestSupport",
@@ -51,7 +51,7 @@ public void shouldFilterOutTracesMiddleBadTraces() {
StackTraceElement[] filtered = filter.filter(t, false);
- assertThat(filtered, hasOnlyThoseClasses("org.test.TestSupport", "org.test.MockitoSampleTest"));
+ assertThat(filtered, hasOnlyThoseClasses("org.test.TestSupport", "org.test.TestSupport", "org.test.MockitoSampleTest"));
}
@Test
| train | train | 2015-12-08T12:52:28 | "2015-11-06T05:47:44Z" | astafev | train |
mockito/mockito/256_342 | mockito/mockito | mockito/mockito/256 | mockito/mockito/342 | [
"keyword_pr_to_issue"
] | 7b62390fec00c46fa8924354c27686a1a44fe2ab | b3648078d7adeb4277bbaf75a87b2a272335d5bf | [
"I think most of us work on Linux/OSX, it probably has to do with the JDK\nversion and windows line endings.\n\nSo minifying this javascript code may work ?\n\n-- Brice\n\nOn Fri, Jul 10, 2015 at 8:19 AM, Meang Akira Tanaka <\nnotifications@github.com> wrote:\n\n> When compiling the mockito project using gradle in a command line in\n> Windows following compile error occurs:\n> \n> javadoc: error - Illegal package name: \" javadoc: error - Illegal package\n> name: \"type=\"\n> javadoc: error - Illegal package name: \"text/javascript\"\n> javadoc: error - Illegal package name: \"src=\"\n> javadoc: error - Illegal package name:\n> \"{@docRoot}/js/jdk6-project-version-insert.js\"\n> javadoc: error - Illegal package name: \">\"\n> javadoc: error - Illegal package name: \" javadoc: error - Illegal package\n> name: \"type=\"\n> javadoc: error - Illegal package name: \"text/javascript\"\n> javadoc: error - Illegal package name: \"src=\"\n> javadoc: error - Illegal package name: \"{@docRoot}/js/jquery-1.7.min.js\"\n> javadoc: error - Illegal package name: \">\"\n> javadoc: error - Illegal package name: \" javadoc: error - Illegal package\n> name: \"type=\"\n> javadoc: error - Illegal package name: \"text/javascript\"\n> javadoc: error - Illegal package name: \"src=\"\n> javadoc: error - Illegal package name:\n> \"{@docRoot}/js/highlight-8.6-java/highlight.pack.js\"\n> javadoc: error - Illegal package name: \">\"\n> javadoc: error - Illegal package name: \" javadoc: error - Illegal package\n> name: \"rel=\"\n> javadoc: error - Illegal package name: \"type=\"\n> javadoc: error - Illegal package name: \"text/css\"\n> javadoc: error - Illegal package name: \"href=\"\n> javadoc: error - Illegal package name:\n> \"{@docRoot}/js/highlight-8.6-java/styles/obsidian.css\"\n> javadoc: error - Illegal package name: \"/>\"\n> javadoc: error - Illegal package name: \" javadoc: error - Illegal package\n> name: \"type=\"\n> javadoc: error - Illegal package name: \"text/javascript\"\n> javadoc: error - Illegal package name: \">\"\n> javadoc: error - Illegal package name: \"=\"\n> javadoc: error - Illegal package name: \"&&\"\n> javadoc: error - Illegal package name: \"parseInt($.browser.version)\"\n> javadoc: error - Illegal package name: \"<\"\n> javadoc: error - Illegal package name: \"9;\"\n> javadoc: error - Illegal package name: \"if(!usingOldIE)\"\n> javadoc: error - Illegal package name: \"{\"\n> javadoc: error - Illegal package name: \"$(\"\n> javadoc: error - Illegal package name: \").append(\"\n> javadoc: error - Illegal package name: \" javadoc: error - Illegal package\n> name: \"icon\\\"\n> javadoc: error - Illegal package name: \" href=\\\"\n> javadoc: error - Illegal package name:\n> \"{@docRoot}/favicon.ico?v=cafebabe\\\"\n> javadoc: error - Illegal package name: \">\"\n> javadoc: error - Illegal package name: \")\"\n> javadoc: error - Illegal package name: \"$(\"\n> javadoc: error - Illegal package name: \",\"\n> javadoc: error - Illegal package name: \"window.parent.document).append(\"\n> javadoc: error - Illegal package name: \" javadoc: error - Illegal package\n> name: \"icon\\\"\n> javadoc: error - Illegal package name: \" href=\\\"\n> javadoc: error - Illegal package name:\n> \"{@docRoot}/favicon.ico?v=cafebabe\\\"\n> javadoc: error - Illegal package name: \">\"\n> javadoc: error - Illegal package name: \")\"\n> javadoc: error - Illegal package name: \"hljs.initHighlightingOnLoad();\"\n> javadoc: error - Illegal package name:\n> \"injectProjectVersionForJavadocJDK6(\"\n> javadoc: error - Illegal package name: \"Mockito 2.0.29-beta API\"\n> javadoc: error - Illegal package name: \",\"\n> javadoc: error - Illegal package name:\n> \"em#mockito-version-header-javadoc7-header\"\n> javadoc: error - Illegal package name: \",\"\n> javadoc: error - Illegal package name:\n> \"em#mockito-version-header-javadoc7-footer\"\n> javadoc: error - Illegal package name: \");\"\n> javadoc: error - Illegal package name: \"}\"\n> javadoc: error - Illegal package name: \"\"\n> javadoc: error - Illegal package name: \"\"\n> javadoc: warning - No source files for package stylesheet\n> javadoc: warning - No source files for package var\n> javadoc: warning - No source files for package usingOldIE\n> javadoc: warning - No source files for package $.browser.msie\n> javadoc: warning - No source files for package head\n> javadoc: warning - No source files for package shortcut\n> javadoc: warning - No source files for package head\n> javadoc: warning - No source files for package shortcut\n> 64 errors\n> 8 warnings\n> \n> I tracked the issue down to gradle/javadoc.gradle where the gradle scripts\n> sets the bottom property to a java script with multiple lines.\n> \n> Changing that to a single line seems to be make it possible to complete\n> the mockitoJavaDoc task without any errors.\n> \n> —\n> Reply to this email directly or view it on GitHub\n> https://github.com/mockito/mockito/issues/256.\n",
"Fixed via 34f8c69\n",
"Hi Brice\n\nUnfortunately it did not work... I have submitted an alternative suggestion\n\nbr\n\nMeang\n"
] | [
"Good idea !\n"
] | "2016-01-20T00:39:52Z" | [] | task mockitoJavadoc fails when compiling in windows | When compiling the mockito project using gradle in a command line in Windows following compile error occurs:
javadoc: error - Illegal package name: "<script"
javadoc: error - Illegal package name: "type="
javadoc: error - Illegal package name: "text/javascript"
javadoc: error - Illegal package name: "src="
javadoc: error - Illegal package name: "{@docRoot}/js/jdk6-project-version-insert.js"
javadoc: error - Illegal package name: "></script>"
javadoc: error - Illegal package name: "<script"
javadoc: error - Illegal package name: "type="
javadoc: error - Illegal package name: "text/javascript"
javadoc: error - Illegal package name: "src="
javadoc: error - Illegal package name: "{@docRoot}/js/jquery-1.7.min.js"
javadoc: error - Illegal package name: "></script>"
javadoc: error - Illegal package name: "<script"
javadoc: error - Illegal package name: "type="
javadoc: error - Illegal package name: "text/javascript"
javadoc: error - Illegal package name: "src="
javadoc: error - Illegal package name: "{@docRoot}/js/highlight-8.6-java/highlight.pack.js"
javadoc: error - Illegal package name: "></script>"
javadoc: error - Illegal package name: "<link"
javadoc: error - Illegal package name: "rel="
javadoc: error - Illegal package name: "type="
javadoc: error - Illegal package name: "text/css"
javadoc: error - Illegal package name: "href="
javadoc: error - Illegal package name: "{@docRoot}/js/highlight-8.6-java/styles/obsidian.css"
javadoc: error - Illegal package name: "/>"
javadoc: error - Illegal package name: "<script"
javadoc: error - Illegal package name: "type="
javadoc: error - Illegal package name: "text/javascript"
javadoc: error - Illegal package name: ">"
javadoc: error - Illegal package name: "="
javadoc: error - Illegal package name: "&&"
javadoc: error - Illegal package name: "parseInt($.browser.version)"
javadoc: error - Illegal package name: "<"
javadoc: error - Illegal package name: "9;"
javadoc: error - Illegal package name: "if(!usingOldIE)"
javadoc: error - Illegal package name: "{"
javadoc: error - Illegal package name: "$("
javadoc: error - Illegal package name: ").append("
javadoc: error - Illegal package name: "<link rel=\"
javadoc: error - Illegal package name: "icon\\"
javadoc: error - Illegal package name: " href=\"
javadoc: error - Illegal package name: "{@docRoot}/favicon.ico?v=cafebabe\\"
javadoc: error - Illegal package name: ">"
javadoc: error - Illegal package name: ")"
javadoc: error - Illegal package name: "$("
javadoc: error - Illegal package name: ","
javadoc: error - Illegal package name: "window.parent.document).append("
javadoc: error - Illegal package name: "<link rel=\"
javadoc: error - Illegal package name: "icon\\"
javadoc: error - Illegal package name: " href=\"
javadoc: error - Illegal package name: "{@docRoot}/favicon.ico?v=cafebabe\\"
javadoc: error - Illegal package name: ">"
javadoc: error - Illegal package name: ")"
javadoc: error - Illegal package name: "hljs.initHighlightingOnLoad();"
javadoc: error - Illegal package name: "injectProjectVersionForJavadocJDK6("
javadoc: error - Illegal package name: "Mockito 2.0.29-beta API"
javadoc: error - Illegal package name: ","
javadoc: error - Illegal package name: "em#mockito-version-header-javadoc7-header"
javadoc: error - Illegal package name: ","
javadoc: error - Illegal package name: "em#mockito-version-header-javadoc7-footer"
javadoc: error - Illegal package name: ");"
javadoc: error - Illegal package name: "}"
javadoc: error - Illegal package name: "</script>"
javadoc: error - Illegal package name: ""
javadoc: warning - No source files for package stylesheet
javadoc: warning - No source files for package var
javadoc: warning - No source files for package usingOldIE
javadoc: warning - No source files for package $.browser.msie
javadoc: warning - No source files for package head
javadoc: warning - No source files for package shortcut
javadoc: warning - No source files for package head
javadoc: warning - No source files for package shortcut
64 errors
8 warnings
I tracked the issue down to gradle/javadoc.gradle where the gradle scripts sets the bottom property to a java script with multiple lines.
Changing that to a single line seems to be make it possible to complete the mockitoJavaDoc task without any errors.
| [
"gradle/javadoc.gradle"
] | [
"gradle/javadoc.gradle"
] | [] | diff --git a/gradle/javadoc.gradle b/gradle/javadoc.gradle
index 55052e9f3e..4d5daa5d43 100644
--- a/gradle/javadoc.gradle
+++ b/gradle/javadoc.gradle
@@ -40,8 +40,8 @@ task mockitoJavadoc(type: Javadoc) {
<script type="text/javascript">
var usingOldIE = \$.browser.msie && parseInt(\$.browser.version) < 9;
if(!usingOldIE) {
- \$("head").append("<link rel=\\"shortcut icon\\" href=\\"{@docRoot}/favicon.ico?v=cafebabe\\">")
- \$("head", window.parent.document).append("<link rel=\\"shortcut icon\\" href=\\"{@docRoot}/favicon.ico?v=cafebabe\\">")
+ \$("head").append("<link rel=\\"shortcut icon\\" href=\\"{@docRoot}/favicon.ico?v=cafebabe\\">");
+ \$("head", window.parent.document).append("<link rel=\\"shortcut icon\\" href=\\"{@docRoot}/favicon.ico?v=cafebabe\\">");
hljs.initHighlightingOnLoad();
\$("pre.code").css("font-size", "0.9em");
injectProjectVersionForJavadocJDK6("Mockito ${project.version} API",
@@ -49,7 +49,7 @@ task mockitoJavadoc(type: Javadoc) {
"em#mockito-version-header-javadoc7-footer");
}
</script>
- """)
+ """.replaceAll(/\r|\n/, ""))
// options.stylesheetFile file("src/javadoc/stylesheet.css")
// options.addStringOption('top', 'some html')
if (JavaVersion.current().isJava8Compatible()) {
| null | test | train | 2016-01-18T21:57:55 | "2015-07-10T06:19:17Z" | mat013 | train |
mockito/mockito/345_349 | mockito/mockito | mockito/mockito/345 | mockito/mockito/349 | [
"keyword_pr_to_issue"
] | c18bf2a94e2e8d95a78cbd5fe18252d39acee8c4 | 455eb2f4737b4f15bd4472cce675d24398975439 | [
"Issue #345 resolves this for atMost verification. What about other verification modes (i.e. times, atLeast)? Are you working on that, @tarnowskijan? Was the issue only for the atMost case? Because in the code from the description you used times instead of atMost.\n",
"@thesnowgoose, unfortunately you're right, the issue is still there when you use times() in combination with after(). I only fixed the problem with after() and atMost() and I don't know why I was focused only on this case. I'll try to fix the whole issue in the near future, but feel free to propose your own solution if you already have one.\n",
"Actually I'm working on it. There is also an issue when you use atLeast(), I'll try to fix it too.\nRegards!!. @tarnowskijan \n",
"Personally, I use extensively timeout and after in my tests, because their use is significantly different. Replace those by a single await can seem interesting at a first glance, but it is actually not.\n",
"@jmborer Could you elaborate ?\n",
"Well I have to test in a lot of asynch situations. Sometimes I need to wait for a interaction, continue quickly if it occurs before a given amount of time and fail otherwise. There I use timeout(). Then I have situations where I want to wait a given time and THEN only do the check. This is where I use after() instead of Thread.sleep()+verify() which I find less fluent to read...\n",
"@jmborer Thanks for the feedback I linked your comment in #472 \n",
"will be fixed with #936 aka `within(duration,timeunit)`",
"Will this be fixed? Mockito 2.19.0 still has this problem and the mentioned pull request which could resolve this (https://github.com/mockito/mockito/pull/936) was put on hold. Please either fix this or provide a way to express the after(x).atLeast(y) without having the argument captor returning a collection with millions [sic] of items via `ArgumentCaptor#getAllValues()` although the method was called only a couple of times.",
"@Trinova #936 needs to be reviewed by a core member, there is nothing I can do as contributor. I don't know if it will ever happen since the core-team is busy and doesn't plan to hire new core member. Maybe the community should fork Mockito and release it with an other group and artefact-id to overcome the prolonged review process. "
] | [] | "2016-02-04T14:45:47Z" | [
"ready"
] | Verification using After and ArgumentCaptor returns unexpected size of captured values list | Hi, I found weird behavior of Mockito (ver. 1.10.19) when verifying method invocation with after() and ArgumentCaptor. The list of captured values returned by ArgumentCaptor has size much bigger than I expect. Moreover this behavior in connection with long timeout leads to exceeding memory limit. Example below. Is it expected behavior or bug?
``` java
package org.mockito.test;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.after;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
public class MockitoAfterFeatureTest {
private RequestSender requestSender;
private RequestProcessor requestProcessor;
private ArgumentCaptor<String> stringArgumentCaptor;
@Before
public void doBeforeTest() {
requestSender = mock(RequestSender.class);
requestProcessor = new RequestProcessor(requestSender);
stringArgumentCaptor = ArgumentCaptor.forClass(String.class);
}
@Test
public void shouldVerifyUsingAfterAndArgumentCaptor() {
// when
requestProcessor.process("first_request");
requestProcessor.process("second_request");
// then
verify(requestSender, after(2500).times(2)).send(stringArgumentCaptor.capture());
assertEquals("first_request", stringArgumentCaptor.getAllValues().get(0));
assertEquals("second_request", stringArgumentCaptor.getAllValues().get(1));
assertEquals(2, stringArgumentCaptor.getAllValues().size());
}
public static class RequestProcessor {
private final RequestSender requestSender;
public RequestProcessor(RequestSender requestSender) {
this.requestSender = requestSender;
}
public void process(String request) {
requestSender.send(request);
}
}
public interface RequestSender {
void send(String request);
}
}
```
| [
"src/main/java/org/mockito/internal/verification/AtMost.java"
] | [
"src/main/java/org/mockito/internal/verification/AtMost.java"
] | [
"src/test/java/org/mockitousage/verification/VerificationAfterDelayTest.java"
] | diff --git a/src/main/java/org/mockito/internal/verification/AtMost.java b/src/main/java/org/mockito/internal/verification/AtMost.java
index 54a5285c47..25a7fc59d1 100644
--- a/src/main/java/org/mockito/internal/verification/AtMost.java
+++ b/src/main/java/org/mockito/internal/verification/AtMost.java
@@ -5,6 +5,7 @@
package org.mockito.internal.verification;
+import java.util.Iterator;
import java.util.List;
import org.mockito.exceptions.Reporter;
@@ -38,7 +39,8 @@ public void verify(VerificationData data) {
if (foundSize > maxNumberOfInvocations) {
new Reporter().wantedAtMostX(maxNumberOfInvocations, foundSize);
}
-
+
+ removeAlreadyVerified(found);
invocationMarker.markVerified(found, wanted);
}
@@ -46,4 +48,13 @@ public void verify(VerificationData data) {
public VerificationMode description(String description) {
return VerificationModeFactory.description(this, description);
}
+
+ private void removeAlreadyVerified(List<Invocation> invocations) {
+ for (Iterator<Invocation> iterator = invocations.iterator(); iterator.hasNext(); ) {
+ Invocation i = iterator.next();
+ if (i.isVerified()) {
+ iterator.remove();
+ }
+ }
+ }
}
\ No newline at end of file
| diff --git a/src/test/java/org/mockitousage/verification/VerificationAfterDelayTest.java b/src/test/java/org/mockitousage/verification/VerificationAfterDelayTest.java
index d20c39d8ba..e0d4f76c71 100644
--- a/src/test/java/org/mockitousage/verification/VerificationAfterDelayTest.java
+++ b/src/test/java/org/mockitousage/verification/VerificationAfterDelayTest.java
@@ -15,6 +15,8 @@
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.exceptions.base.MockitoAssertionError;
import org.mockitoutil.TestBase;
@@ -29,6 +31,9 @@ public class VerificationAfterDelayTest extends TestBase {
private List<Exception> exceptions = new LinkedList<Exception>();
+ @Captor
+ private ArgumentCaptor<String> stringArgumentCaptor;
+
@After
public void teardown() {
// making sure there are no threading related exceptions
@@ -106,6 +111,31 @@ public void shouldStopEarlyIfTestIsDefinitelyFailed() throws Exception {
verify(mock, after(10000).never()).clear();
}
+ /**
+ * Test for issue #345.
+ */
+ @Test
+ public void shouldReturnListOfArgumentsWithSameSizeAsGivenInAtMostVerification() {
+ // given
+ int n = 3;
+
+ // when
+ exerciseMockNTimes(n);
+
+ // then
+ verify(mock, after(200).atMost(n)).add(stringArgumentCaptor.capture());
+ assertEquals(n, stringArgumentCaptor.getAllValues().size());
+ assertEquals("0", stringArgumentCaptor.getAllValues().get(0));
+ assertEquals("1", stringArgumentCaptor.getAllValues().get(1));
+ assertEquals("2", stringArgumentCaptor.getAllValues().get(2));
+ }
+
+ private void exerciseMockNTimes(int n) {
+ for (int i = 0; i < n; i++) {
+ mock.add(String.valueOf(i));
+ }
+ }
+
private Thread waitAndExerciseMock(final int sleep) {
Thread t = new Thread() {
| test | train | 2016-01-26T23:52:50 | "2016-01-26T22:23:46Z" | tarnowskijan | train |
mockito/mockito/365_373 | mockito/mockito | mockito/mockito/365 | mockito/mockito/373 | [
"keyword_pr_to_issue"
] | 196ff979da156caa07e19f57e4849637d8bede1a | f2ec9da14192fa98f534dd8e01d4921fcc5c8c14 | [
"I would like to mention that sometimes class argument can be useful.\r\n\r\nIn my case I would like to catch object passed to mock and write to mongo database.\r\nThe code I would like to have is:\r\n\r\n```\r\n// test setup\r\ndoAnswer(invocation -> mongoTemplate.insert(invocation.getArgument(0, Person.class)))\r\n .when(mock)\r\n .myMethod(any());\r\n\r\n// test execution \r\nmock.myMethod(new Person(\"Joe\", \"Doe\"))\r\n```\r\nThe reason of problem is that `MongoTemplate` has 2 similar methods:\r\n```\r\npublic <T> ExecutableInsert<T> insert(Class<T> domainType) {...) //(1)\r\npublic void insert(Object objectToSave) {..) //(2)\r\n```\r\nAFAIU, when I setup `doAnswer(invocation -> mongoTemplate.insert(invocation.getArgument(0))`, type inference will choose method (1) and finally I get class cast exception `Person` -> `Class`\r\n\r\nUnfortunately, code `doAnswer(invocation -> mongoTemplate.insert((Person)invocation.getArgument(0))` does not compile\r\n\r\nTo implement my test, I have to define anonymous class `Answer` so my code is long-winded - one-liner looks much better\r\n"
] | [] | "2016-03-11T20:56:56Z" | [
"1.* incompatible"
] | Simplify the InvocationOnMock-API to get a casted argument | The 2nd argument of `InvocationOnMock.getArgumentAt(int,Class<T>)` can be removed cause it is not neccessary.
Intuitively on would write this to get a "auto casted" argument:
`String text = invocation.getArgumentAt(1,String.class)`
The type can be ommited without side effects (the implementation of InvocationOnMock discards it anyway).
`String text = invocation.getArgumentAt(1,null)`
Therefore Mockito 2.0 should consider to simplify the API and ommit the `Class`-argument here. Maybe it is also a good chance to simplify the method name too. What about `getArgument(int index)` ?
This is how the 'new' API could look like:
`String text = invocation.getArgument(1)`
| [
"src/main/java/org/mockito/internal/creation/bytebuddy/InterceptedInvocation.java",
"src/main/java/org/mockito/internal/invocation/InvocationImpl.java",
"src/main/java/org/mockito/internal/invocation/InvocationMatcher.java",
"src/main/java/org/mockito/internal/stubbing/answers/ReturnsArgumentAt.java",
"src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsEmptyValues.java",
"src/main/java/org/mockito/invocation/InvocationOnMock.java"
] | [
"src/main/java/org/mockito/internal/creation/bytebuddy/InterceptedInvocation.java",
"src/main/java/org/mockito/internal/invocation/InvocationImpl.java",
"src/main/java/org/mockito/internal/invocation/InvocationMatcher.java",
"src/main/java/org/mockito/internal/stubbing/answers/ReturnsArgumentAt.java",
"src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsEmptyValues.java",
"src/main/java/org/mockito/invocation/InvocationOnMock.java"
] | [
"src/test/java/org/mockito/internal/AllInvocationsFinderTest.java",
"src/test/java/org/mockito/internal/invocation/InvocationImplTest.java",
"src/test/java/org/mockitousage/PlaygroundWithDemoOfUnclonedParametersProblemTest.java",
"src/test/java/org/mockitousage/customization/BDDMockitoTest.java",
"src/test/java/org/mockitousage/stubbing/StubbingWithCustomAnswerTest.java"
] | diff --git a/src/main/java/org/mockito/internal/creation/bytebuddy/InterceptedInvocation.java b/src/main/java/org/mockito/internal/creation/bytebuddy/InterceptedInvocation.java
index b0687142e3..8445e4b70b 100644
--- a/src/main/java/org/mockito/internal/creation/bytebuddy/InterceptedInvocation.java
+++ b/src/main/java/org/mockito/internal/creation/bytebuddy/InterceptedInvocation.java
@@ -113,9 +113,14 @@ public Object[] getArguments() {
}
@Override
- @SuppressWarnings("unchecked")
+ @Deprecated
public <T> T getArgumentAt(int index, Class<T> clazz) {
- return (T) arguments[index];
+ return (T) getArgument(index);
+ }
+
+ @Override
+ public <T> T getArgument(int index) {
+ return (T)arguments[index];
}
@Override
diff --git a/src/main/java/org/mockito/internal/invocation/InvocationImpl.java b/src/main/java/org/mockito/internal/invocation/InvocationImpl.java
index dc77a57e25..b7bf096249 100644
--- a/src/main/java/org/mockito/internal/invocation/InvocationImpl.java
+++ b/src/main/java/org/mockito/internal/invocation/InvocationImpl.java
@@ -62,10 +62,17 @@ public Object[] getArguments() {
return arguments;
}
+ @Deprecated
public <T> T getArgumentAt(int index, Class<T> clazz) {
- return (T) arguments[index];
+ return (T) getArgument(index);
}
+ public <T> T getArgument(int index) {
+ return (T)arguments[index];
+ }
+
+
+
public boolean isVerified() {
return verified || isIgnoredForVerification;
}
diff --git a/src/main/java/org/mockito/internal/invocation/InvocationMatcher.java b/src/main/java/org/mockito/internal/invocation/InvocationMatcher.java
index a18f1b62e2..112c7dd5a9 100644
--- a/src/main/java/org/mockito/internal/invocation/InvocationMatcher.java
+++ b/src/main/java/org/mockito/internal/invocation/InvocationMatcher.java
@@ -122,7 +122,7 @@ private void captureRegularArguments(Invocation invocation) {
for (int position = 0; position < regularArgumentsSize(invocation); position++) {
ArgumentMatcher m = matchers.get(position);
if (m instanceof CapturesArguments) {
- ((CapturesArguments) m).captureFrom(invocation.getArgumentAt(position, Object.class));
+ ((CapturesArguments) m).captureFrom(invocation.getArgument(position));
}
}
}
diff --git a/src/main/java/org/mockito/internal/stubbing/answers/ReturnsArgumentAt.java b/src/main/java/org/mockito/internal/stubbing/answers/ReturnsArgumentAt.java
index 059074d254..6db6db8899 100644
--- a/src/main/java/org/mockito/internal/stubbing/answers/ReturnsArgumentAt.java
+++ b/src/main/java/org/mockito/internal/stubbing/answers/ReturnsArgumentAt.java
@@ -39,7 +39,7 @@ public ReturnsArgumentAt(int wantedArgumentPosition) {
public Object answer(InvocationOnMock invocation) throws Throwable {
validateIndexWithinInvocationRange(invocation);
- return invocation.getArguments()[actualArgumentPosition(invocation)];
+ return invocation.getArgument(actualArgumentPosition(invocation));
}
diff --git a/src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsEmptyValues.java b/src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsEmptyValues.java
index 11304afce1..4b8b9474c5 100644
--- a/src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsEmptyValues.java
+++ b/src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsEmptyValues.java
@@ -72,7 +72,7 @@ public Object answer(InvocationOnMock invocation) {
//see issue 184.
//mocks by default should return 0 if references are the same, otherwise some other value because they are not the same. Hence we return 1 (anything but 0 is good).
//Only for compareTo() method by the Comparable interface
- return invocation.getMock() == invocation.getArguments()[0] ? 0 : 1;
+ return invocation.getMock() == invocation.getArgument(0) ? 0 : 1;
}
Class<?> returnType = invocation.getMethod().getReturnType();
diff --git a/src/main/java/org/mockito/invocation/InvocationOnMock.java b/src/main/java/org/mockito/invocation/InvocationOnMock.java
index 815b8a4422..95f7667c5d 100644
--- a/src/main/java/org/mockito/invocation/InvocationOnMock.java
+++ b/src/main/java/org/mockito/invocation/InvocationOnMock.java
@@ -41,9 +41,18 @@ public interface InvocationOnMock extends Serializable {
* @param index argument position
* @param clazz argument type
* @return casted argument on position
+ * @deprecated use {@link #getArgument(int)}
*/
+ @Deprecated
<T> T getArgumentAt(int index, Class<T> clazz);
+ /**
+ * Returns casted argument at the given index
+ * @param index argument index
+ * @return casted argument at the given index
+ */
+ <T> T getArgument(int index);
+
/**
* calls real method
| diff --git a/src/test/java/org/mockito/internal/AllInvocationsFinderTest.java b/src/test/java/org/mockito/internal/AllInvocationsFinderTest.java
index c5230db380..8eea369948 100644
--- a/src/test/java/org/mockito/internal/AllInvocationsFinderTest.java
+++ b/src/test/java/org/mockito/internal/AllInvocationsFinderTest.java
@@ -54,6 +54,6 @@ public void shouldNotCountDuplicatedInteractions() throws Exception {
}
private void assertArgumentEquals(Object argumentValue, Invocation invocation) {
- assertEquals(argumentValue, invocation.getArguments()[0]);
+ assertEquals(argumentValue, invocation.getArgument(0));
}
}
\ No newline at end of file
diff --git a/src/test/java/org/mockito/internal/invocation/InvocationImplTest.java b/src/test/java/org/mockito/internal/invocation/InvocationImplTest.java
index 0317dea5fe..57f229fd32 100644
--- a/src/test/java/org/mockito/internal/invocation/InvocationImplTest.java
+++ b/src/test/java/org/mockito/internal/invocation/InvocationImplTest.java
@@ -156,7 +156,7 @@ public void shouldReturnCastedArgumentAt(){
argTypes(int.class, int.class).args(1, argument).toInvocation();
//when
- int secondArgument = invocationOnInterface.getArgumentAt(1, int.class);
+ int secondArgument = invocationOnInterface.getArgument(1);
//then
assertTrue(secondArgument == argument);
diff --git a/src/test/java/org/mockitousage/PlaygroundWithDemoOfUnclonedParametersProblemTest.java b/src/test/java/org/mockitousage/PlaygroundWithDemoOfUnclonedParametersProblemTest.java
index 882d235c81..a446bda754 100644
--- a/src/test/java/org/mockitousage/PlaygroundWithDemoOfUnclonedParametersProblemTest.java
+++ b/src/test/java/org/mockitousage/PlaygroundWithDemoOfUnclonedParametersProblemTest.java
@@ -75,7 +75,7 @@ public void shouldAlterFinalLog() {
private Answer byCheckingLogEquals(final ImportLogBean status) {
return new Answer() {
public Object answer(InvocationOnMock invocation) throws Throwable {
- ImportLogBean bean = (ImportLogBean) invocation.getArguments()[0];
+ ImportLogBean bean = invocation.getArgument(0);
assertEquals(status, bean);
return null;
}
diff --git a/src/test/java/org/mockitousage/customization/BDDMockitoTest.java b/src/test/java/org/mockitousage/customization/BDDMockitoTest.java
index b74487ef04..b932bd0b33 100644
--- a/src/test/java/org/mockitousage/customization/BDDMockitoTest.java
+++ b/src/test/java/org/mockitousage/customization/BDDMockitoTest.java
@@ -68,7 +68,7 @@ public void should_stub_with_throwable_classes() throws Exception {
public void should_stub_with_answer() throws Exception {
given(mock.simpleMethod(anyString())).willAnswer(new Answer<String>() {
public String answer(InvocationOnMock invocation) throws Throwable {
- return (String) invocation.getArguments()[0];
+ return invocation.getArgument(0);
}});
Assertions.assertThat(mock.simpleMethod("foo")).isEqualTo("foo");
@@ -78,7 +78,7 @@ public String answer(InvocationOnMock invocation) throws Throwable {
public void should_stub_with_will_answer_alias() throws Exception {
given(mock.simpleMethod(anyString())).will(new Answer<String>() {
public String answer(InvocationOnMock invocation) throws Throwable {
- return (String) invocation.getArguments()[0];
+ return invocation.getArgument(0);
}
});
@@ -184,7 +184,7 @@ public void should_stub_using_do_return_style() throws Exception {
public void should_stub_using_do_answer_style() throws Exception {
willAnswer(new Answer<String>() {
public String answer(InvocationOnMock invocation) throws Throwable {
- return (String) invocation.getArguments()[0];
+ return invocation.getArgument(0);
}
})
.given(mock).simpleMethod(anyString());
diff --git a/src/test/java/org/mockitousage/stubbing/StubbingWithCustomAnswerTest.java b/src/test/java/org/mockitousage/stubbing/StubbingWithCustomAnswerTest.java
index 8ca965d148..10486b7971 100644
--- a/src/test/java/org/mockitousage/stubbing/StubbingWithCustomAnswerTest.java
+++ b/src/test/java/org/mockitousage/stubbing/StubbingWithCustomAnswerTest.java
@@ -28,7 +28,7 @@ public class StubbingWithCustomAnswerTest extends TestBase {
public void shouldAnswer() throws Exception {
when(mock.simpleMethod(anyString())).thenAnswer(new Answer<String>() {
public String answer(InvocationOnMock invocation) throws Throwable {
- String arg = (String) invocation.getArguments()[0];
+ String arg = invocation.getArgument(0);
return invocation.getMethod().getName() + "-" + arg;
}
| val | train | 2016-03-09T16:56:37 | "2016-03-01T12:19:49Z" | ChristianSchwarz | train |
mockito/mockito/379_380 | mockito/mockito | mockito/mockito/379 | mockito/mockito/380 | [
"keyword_issue_to_pr",
"keyword_pr_to_issue"
] | 196ff979da156caa07e19f57e4849637d8bede1a | 31c7876f0693a1335c8e41b340e8580aa9a510ae | [
"@thesnowgoose \nThat a bug in VerificationOverTimeImpl#verify(VerificationData). The passed `VerificationData` contains all invocations, in your case \"0\",\"1\" and \"2\". During the specified 200ms these invocations are verified in a loop without delay. That means if your CPU is able to verify the VerificationData 10,000 times during that 200ms the captor captures 30,000 arguments (10000 \\* 3 arguments ). \n\nThe implementation of `After` uses `VerificationOverTimeImpl` and that class performs the verify-loop until the time is elapsed. This behaviour is fine for `Timeout` but violates the specification of `Mockito.after(long)`, this is what the JavaDoc says:\n\n> Allows verifying over a given period. It causes a verify to **wait for a specified period of time** for a desired interaction\n\nIn other words the `After` implementation must use some kind of `VerificationAfterDelayImpl`, that simply waits and than verify the invocations.\n\nI have a solution and will provide a PR.\n",
"PR #380 relates to this issue.\n",
"Fixed by #380 \n",
"Why is this closed? I ran into the issue and lost about an hour before realizing it is a Mockito bug. What is the current status? It is not fixed in the 1.x branch. I am using 1.10.19 which seems the most recent version.\n",
"@jmborer can you test it with the latest 2.0.0-beta build, it should be fixed\n",
"OK. Thanx for the info, but I don't feel confortable to use a beta version to test operational sofware...\n",
"The beta is almost over, I hope to publish a release candidate in the\ncoming days. You should be able to upgrade without much problems, since the\nbreaking changes are kept at a minimum.\n\nOn Thu, 18 Aug 2016, 16:12 Jean-Marc Borer, notifications@github.com\nwrote:\n\n> OK. Thanx for the info, but I don't feel confortable to use a beta version\n> to test operational sofware...\n> \n> —\n> You are receiving this because you are subscribed to this thread.\n> Reply to this email directly, view it on GitHub\n> https://github.com/mockito/mockito/issues/379#issuecomment-240735180,\n> or mute the thread\n> https://github.com/notifications/unsubscribe-auth/AFrDb3NREzSakS3dFBKOKP-cyi5DMdb5ks5qhGhXgaJpZM4H4c7l\n> .\n",
"@jmborer mockito 2 beta is fairly stable, the API should not move much. Yet there's some incompatible change with 1.x\n\n> I don't feel confortable to use a beta version to test operational sofware...\n\nRemember it's for tests not to run on your production servers/containers\n",
"Sure. I won't use in production. I'll wait a little until RC is out to do the migration. I already noticed it is no longer compatible with PowerMock. I have to check if I need it anymore then my problem is solved. \n",
"Was this actually merged into a release? I initially found the issue while running 2.0.41-beta, so I tried 2.4.0 and 2.8.9, but I'm still seeing the issue, specifically with after() and times(). \r\n\r\n",
"Still encounter this issue in 3.6.0 (also tested latest 3.12.4) when using `after()`"
] | [
"Since this method is duplicate from the method added in the class below, maybe we can extract an superclass `InvocationsChecker`. This class abstracts away all the logic regarding obtaining and reporting the failures, the constructor as well as this new method.\n"
] | "2016-03-25T01:04:42Z" | [
"enhancement"
] | Verification using After and ArgumentCaptor with Times or AtLeast methods returns unexpected size of captured values list. | Hi!
I was looking issue #345 and found that the test "shouldReturnListOfArgumentsWithSameSizeAsGivenInAtMostVerification" (located in VerificationAfterDelayTest.java) fails if you use atLeast() or times() instead of atMost().
I created these tests:
![screenshot from 2016-03-24 16 50 29](https://cloud.githubusercontent.com/assets/17257307/14034443/8a3d8b98-f1e0-11e5-856a-65dc20a4fa6b.png)
| [
"src/main/java/org/mockito/internal/verification/Times.java",
"src/main/java/org/mockito/internal/verification/checkers/AtLeastXNumberOfInvocationsChecker.java",
"src/main/java/org/mockito/internal/verification/checkers/NumberOfInvocationsChecker.java"
] | [
"src/main/java/org/mockito/internal/verification/Times.java",
"src/main/java/org/mockito/internal/verification/checkers/AtLeastXNumberOfInvocationsChecker.java",
"src/main/java/org/mockito/internal/verification/checkers/NumberOfInvocationsChecker.java"
] | [
"src/test/java/org/mockitousage/verification/VerificationAfterDelayTest.java"
] | diff --git a/src/main/java/org/mockito/internal/verification/Times.java b/src/main/java/org/mockito/internal/verification/Times.java
index 62a7ed753f..f43ce4286c 100644
--- a/src/main/java/org/mockito/internal/verification/Times.java
+++ b/src/main/java/org/mockito/internal/verification/Times.java
@@ -31,12 +31,16 @@ public Times(int wantedNumberOfInvocations) {
}
public void verify(VerificationData data) {
+ List<Invocation> invocations = data.getAllInvocations();
+ InvocationMatcher wanted = data.getWanted();
+
if (wantedCount > 0) {
MissingInvocationChecker missingInvocation = new MissingInvocationChecker();
- missingInvocation.check(data.getAllInvocations(), data.getWanted());
+ missingInvocation.check(invocations, wanted);
}
+
NumberOfInvocationsChecker numberOfInvocations = new NumberOfInvocationsChecker();
- numberOfInvocations.check(data.getAllInvocations(), data.getWanted(), wantedCount);
+ numberOfInvocations.check(invocations, wanted, wantedCount);
}
public void verifyInOrder(VerificationDataInOrder data) {
diff --git a/src/main/java/org/mockito/internal/verification/checkers/AtLeastXNumberOfInvocationsChecker.java b/src/main/java/org/mockito/internal/verification/checkers/AtLeastXNumberOfInvocationsChecker.java
index cc29e0963c..f21489edf8 100644
--- a/src/main/java/org/mockito/internal/verification/checkers/AtLeastXNumberOfInvocationsChecker.java
+++ b/src/main/java/org/mockito/internal/verification/checkers/AtLeastXNumberOfInvocationsChecker.java
@@ -5,6 +5,7 @@
package org.mockito.internal.verification.checkers;
+import java.util.Iterator;
import java.util.List;
import org.mockito.exceptions.Reporter;
@@ -28,7 +29,17 @@ public void check(List<Invocation> invocations, InvocationMatcher wanted, int wa
Location lastLocation = finder.getLastLocation(actualInvocations);
reporter.tooLittleActualInvocations(new AtLeastDiscrepancy(wantedCount, actualCount), wanted, lastLocation);
}
-
+
+ removeAlreadyVerified(actualInvocations);
invocationMarker.markVerified(actualInvocations, wanted);
}
+
+ private void removeAlreadyVerified(List<Invocation> invocations) {
+ for (Iterator<Invocation> iterator = invocations.iterator(); iterator.hasNext(); ) {
+ Invocation i = iterator.next();
+ if (i.isVerified()) {
+ iterator.remove();
+ }
+ }
+ }
}
\ No newline at end of file
diff --git a/src/main/java/org/mockito/internal/verification/checkers/NumberOfInvocationsChecker.java b/src/main/java/org/mockito/internal/verification/checkers/NumberOfInvocationsChecker.java
index 17dec9ff2e..2529095c46 100644
--- a/src/main/java/org/mockito/internal/verification/checkers/NumberOfInvocationsChecker.java
+++ b/src/main/java/org/mockito/internal/verification/checkers/NumberOfInvocationsChecker.java
@@ -5,6 +5,7 @@
package org.mockito.internal.verification.checkers;
+import java.util.Iterator;
import java.util.List;
import org.mockito.exceptions.Reporter;
@@ -44,7 +45,17 @@ public void check(List<Invocation> invocations, InvocationMatcher wanted, int wa
Location firstUndesired = actualInvocations.get(wantedCount).getLocation();
reporter.tooManyActualInvocations(wantedCount, actualCount, wanted, firstUndesired);
}
-
+
+ removeAlreadyVerified(actualInvocations);
invocationMarker.markVerified(actualInvocations, wanted);
}
+
+ private void removeAlreadyVerified(List<Invocation> invocations) {
+ for (Iterator<Invocation> iterator = invocations.iterator(); iterator.hasNext(); ) {
+ Invocation i = iterator.next();
+ if (i.isVerified()) {
+ iterator.remove();
+ }
+ }
+ }
}
\ No newline at end of file
| diff --git a/src/test/java/org/mockitousage/verification/VerificationAfterDelayTest.java b/src/test/java/org/mockitousage/verification/VerificationAfterDelayTest.java
index e0d4f76c71..2462f28e45 100644
--- a/src/test/java/org/mockitousage/verification/VerificationAfterDelayTest.java
+++ b/src/test/java/org/mockitousage/verification/VerificationAfterDelayTest.java
@@ -130,6 +130,38 @@ public void shouldReturnListOfArgumentsWithSameSizeAsGivenInAtMostVerification()
assertEquals("2", stringArgumentCaptor.getAllValues().get(2));
}
+ @Test
+ public void shouldReturnListOfArgumentsWithSameSizeAsGivenInTimesVerification() {
+ // given
+ int n = 3;
+
+ // when
+ exerciseMockNTimes(n);
+
+ //Then
+ verify(mock, after(200).times(n)).add(stringArgumentCaptor.capture());
+ assertEquals(n, stringArgumentCaptor.getAllValues().size());
+ assertEquals("0", stringArgumentCaptor.getAllValues().get(0));
+ assertEquals("1", stringArgumentCaptor.getAllValues().get(1));
+ assertEquals("2", stringArgumentCaptor.getAllValues().get(2));
+ }
+
+ @Test
+ public void shouldReturnListOfArgumentsWithSameSizeAsGivenInAtLeastVerification() {
+ // given
+ int n = 3;
+
+ // when
+ exerciseMockNTimes(n);
+
+ //Then
+ verify(mock, after(200).atLeast(n)).add(stringArgumentCaptor.capture());
+ assertEquals(n, stringArgumentCaptor.getAllValues().size());
+ assertEquals("0", stringArgumentCaptor.getAllValues().get(0));
+ assertEquals("1", stringArgumentCaptor.getAllValues().get(1));
+ assertEquals("2", stringArgumentCaptor.getAllValues().get(2));
+ }
+
private void exerciseMockNTimes(int n) {
for (int i = 0; i < n; i++) {
mock.add(String.valueOf(i));
| train | train | 2016-03-09T16:56:37 | "2016-03-24T23:42:00Z" | thesnowgoose | train |
mockito/mockito/374_386 | mockito/mockito | mockito/mockito/374 | mockito/mockito/386 | [
"keyword_pr_to_issue"
] | 196ff979da156caa07e19f57e4849637d8bede1a | 66a7205945d201e01aa6043d5cfe1aa0ae08e622 | [] | [] | "2016-04-09T19:47:00Z" | [] | Remove deprecated API from Mockito 2 | # This is a reminder to remove all deprecated API's from the upcoming mockito 2.
This issue blocks #123 [Release Mockito 2.0](123)
Relates to
- #273 [Get rid of ReturnValues](273)
| [
"src/main/java/org/mockito/Answers.java",
"src/main/java/org/mockito/ArgumentCaptor.java",
"src/main/java/org/mockito/exceptions/Discrepancy.java",
"src/main/java/org/mockito/exceptions/Pluralizer.java",
"src/main/java/org/mockito/exceptions/PrintableInvocation.java",
"src/main/java/org/mockito/exceptions/verification/junit/JUnitTool.java",
"src/main/java/org/mockito/invocation/DescribedInvocation.java",
"src/main/java/org/mockito/listeners/MethodInvocationReport.java",
"src/main/java/org/mockito/runners/MockitoJUnit44Runner.java",
"src/main/java/org/mockito/stubbing/answers/ReturnsElementsOf.java"
] | [
"src/main/java/org/mockito/Answers.java",
"src/main/java/org/mockito/ArgumentCaptor.java",
"src/main/java/org/mockito/invocation/DescribedInvocation.java",
"src/main/java/org/mockito/listeners/MethodInvocationReport.java"
] | [
"src/test/java/org/mockito/runners/RunnersValidateFrameworkUsageTest.java",
"src/test/java/org/mockitousage/matchers/CapturingArgumentsTest.java",
"src/test/java/org/mockitousage/stacktrace/PointingStackTraceToActualInvocationTest.java",
"src/test/java/org/mockitousage/stubbing/StubbingWithExtraAnswersTest.java"
] | diff --git a/src/main/java/org/mockito/Answers.java b/src/main/java/org/mockito/Answers.java
index db3f5723ad..ff89b4b482 100644
--- a/src/main/java/org/mockito/Answers.java
+++ b/src/main/java/org/mockito/Answers.java
@@ -87,15 +87,6 @@ public enum Answers implements Answer<Object>{
this.implementation = implementation;
}
- /**
- * @deprecated Use the enum-constant directly, instead of this getter. This method will be removed in a future release<br>
- * E.g. instead of <code>Answers.CALLS_REAL_METHODS.get()</code> use <code>Answers.CALLS_REAL_METHODS</code> .
- */
- @Deprecated
- public Answer<Object> get() {
- return this;
- }
-
public Object answer(InvocationOnMock invocation) throws Throwable {
return implementation.answer(invocation);
}
diff --git a/src/main/java/org/mockito/ArgumentCaptor.java b/src/main/java/org/mockito/ArgumentCaptor.java
index e84de14c83..0bf639d414 100644
--- a/src/main/java/org/mockito/ArgumentCaptor.java
+++ b/src/main/java/org/mockito/ArgumentCaptor.java
@@ -65,26 +65,6 @@ public class ArgumentCaptor<T> {
private final CapturingMatcher<T> capturingMatcher = new CapturingMatcher<T>();
private final Class<? extends T> clazz;
- /**
- * @deprecated
- *
- * <b>Please use factory method {@link ArgumentCaptor#forClass(Class)} to create captors</b>
- * <p>
- * This is required to avoid NullPointerExceptions when autoUnboxing primitive types.
- * See issue 99.
- * <p>
- * Example:
- * <pre class="code"><code class="java">
- * ArgumentCaptor<Person> argument = ArgumentCaptor.forClass(Person.class);
- * verify(mock).doSomething(argument.capture());
- * assertEquals("John", argument.getValue().getName());
- * </code></pre>
- */
- @Deprecated
- public ArgumentCaptor() {
- this.clazz = null;
- }
-
private ArgumentCaptor(Class<? extends T> clazz) {
this.clazz = clazz;
}
diff --git a/src/main/java/org/mockito/exceptions/Discrepancy.java b/src/main/java/org/mockito/exceptions/Discrepancy.java
deleted file mode 100644
index 4b3e4d7f2d..0000000000
--- a/src/main/java/org/mockito/exceptions/Discrepancy.java
+++ /dev/null
@@ -1,17 +0,0 @@
-/*
- * Copyright (c) 2007 Mockito contributors
- * This program is made available under the terms of the MIT License.
- */
-package org.mockito.exceptions;
-
-@Deprecated
-/**
- * @Deprecated. This class has been moved to internal packages because it was never meant to be public.
- * If you need it for extending Mockito please let us know. You can still use {@link org.mockito.internal.reporting.Discrepancy}.
- * However, the package clearly states that the class in a part of a public API so it can change.
- */
-public class Discrepancy extends org.mockito.internal.reporting.Discrepancy {
- public Discrepancy(int wantedCount, int actualCount) {
- super(wantedCount, actualCount);
- }
-}
\ No newline at end of file
diff --git a/src/main/java/org/mockito/exceptions/Pluralizer.java b/src/main/java/org/mockito/exceptions/Pluralizer.java
deleted file mode 100644
index 0dcecee5e9..0000000000
--- a/src/main/java/org/mockito/exceptions/Pluralizer.java
+++ /dev/null
@@ -1,13 +0,0 @@
-/*
- * Copyright (c) 2007 Mockito contributors
- * This program is made available under the terms of the MIT License.
- */
-package org.mockito.exceptions;
-
-@Deprecated
-/**
- * @Deprecated. This class has been moved to internal packages because it was never meant to be public.
- * If you need it for extending Mockito please let us know. You can still use {@link org.mockito.internal.reporting.Pluralizer}.
- * However, the package clearly states that the class in a part of a public API so it can change.
- */
-public class Pluralizer extends org.mockito.internal.reporting.Pluralizer {}
diff --git a/src/main/java/org/mockito/exceptions/PrintableInvocation.java b/src/main/java/org/mockito/exceptions/PrintableInvocation.java
deleted file mode 100644
index 52e288ddc8..0000000000
--- a/src/main/java/org/mockito/exceptions/PrintableInvocation.java
+++ /dev/null
@@ -1,22 +0,0 @@
-/*
- * Copyright (c) 2007 Mockito contributors
- * This program is made available under the terms of the MIT License.
- */
-
-package org.mockito.exceptions;
-
-import org.mockito.invocation.DescribedInvocation;
-import org.mockito.invocation.Location;
-
-@Deprecated
-/**
- * @Deprecated. We needed to move this class to a better place to keep consistency of the API.
- * Please use {@link DescribedInvocation} instead.
- */
-public interface PrintableInvocation {
-
- String toString();
-
- Location getLocation();
-
-}
\ No newline at end of file
diff --git a/src/main/java/org/mockito/exceptions/verification/junit/JUnitTool.java b/src/main/java/org/mockito/exceptions/verification/junit/JUnitTool.java
deleted file mode 100644
index f5c614a3d3..0000000000
--- a/src/main/java/org/mockito/exceptions/verification/junit/JUnitTool.java
+++ /dev/null
@@ -1,22 +0,0 @@
-/*
- * Copyright (c) 2007 Mockito contributors
- * This program is made available under the terms of the MIT License.
- */
-package org.mockito.exceptions.verification.junit;
-
-@Deprecated
-/**
- * @Deprecated. This class has been moved to internal packages because it was never meant to be public.
- * If you need it for extending Mockito please let us know. You can still use {@link org.mockito.internal.junit.JUnitTool}.
- * However, the package clearly states that the class in a part of a public API so it can change.
- */
-public class JUnitTool {
-
- public static boolean hasJUnit() {
- return org.mockito.internal.junit.JUnitTool.hasJUnit();
- }
-
- public static AssertionError createArgumentsAreDifferentException(String message, String wanted, String actual) {
- return org.mockito.internal.junit.JUnitTool.createArgumentsAreDifferentException(message, wanted, actual);
- }
-}
\ No newline at end of file
diff --git a/src/main/java/org/mockito/invocation/DescribedInvocation.java b/src/main/java/org/mockito/invocation/DescribedInvocation.java
index b18223560b..fc975aba44 100644
--- a/src/main/java/org/mockito/invocation/DescribedInvocation.java
+++ b/src/main/java/org/mockito/invocation/DescribedInvocation.java
@@ -4,12 +4,11 @@
*/
package org.mockito.invocation;
-import org.mockito.exceptions.PrintableInvocation;
/**
* Provides information about the invocation, specifically a human readable description and the location.
*/
-public interface DescribedInvocation extends PrintableInvocation {
+public interface DescribedInvocation {
/**
* Describes the invocation in the human friendly way.
diff --git a/src/main/java/org/mockito/listeners/MethodInvocationReport.java b/src/main/java/org/mockito/listeners/MethodInvocationReport.java
index da171ba911..a7303e892b 100644
--- a/src/main/java/org/mockito/listeners/MethodInvocationReport.java
+++ b/src/main/java/org/mockito/listeners/MethodInvocationReport.java
@@ -4,7 +4,6 @@
*/
package org.mockito.listeners;
-import org.mockito.exceptions.PrintableInvocation;
import org.mockito.invocation.DescribedInvocation;
/**
@@ -18,10 +17,6 @@
*/
public interface MethodInvocationReport {
/**
- * The return type is deprecated, please assign the return value from this method
- * to the {@link DescribedInvocation} type. Sorry for inconvenience but we had to move
- * {@link PrintableInvocation} to better place to keep the API consistency.
- *
* @return Information on the method call, never {@code null}
*/
DescribedInvocation getInvocation();
diff --git a/src/main/java/org/mockito/runners/MockitoJUnit44Runner.java b/src/main/java/org/mockito/runners/MockitoJUnit44Runner.java
deleted file mode 100644
index 4080d1ef8e..0000000000
--- a/src/main/java/org/mockito/runners/MockitoJUnit44Runner.java
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * Copyright (c) 2007 Mockito contributors
- * This program is made available under the terms of the MIT License.
- */
-
-package org.mockito.runners;
-
-import org.mockito.Mock;
-import org.mockito.Mockito;
-import org.mockito.MockitoAnnotations;
-
-import java.lang.reflect.InvocationTargetException;
-
-/**
- * <b>Deprecated: Simply use {@link MockitoJUnitRunner}</b>
- * <p>
- * Compatible only with <b>JUnit 4.4</b>, this runner adds following behavior:
- * <ul>
- * <li>
- * Initializes mocks annotated with {@link Mock},
- * so that explicit usage of {@link MockitoAnnotations#initMocks(Object)} is not necessary.
- * Mocks are initialized before each test method.
- * <li>
- * validates framework usage after each test method. See javadoc for {@link Mockito#validateMockitoUsage()}.
- * </ul>
- *
- * Runner is completely optional - there are other ways you can get @Mock working, for example by writing a base class.
- * Explicitly validating framework usage is also optional because it is triggered automatically by Mockito every time you use the framework.
- * See javadoc for {@link Mockito#validateMockitoUsage()}.
- * <p>
- * Read more about @Mock annotation in javadoc for {@link MockitoAnnotations}
- * <p>
- * Example:
- * <pre class="code"><code class="java">
- * @RunWith(MockitoJUnitRunner.class)
- * public class ExampleTest {
- *
- * @Mock
- * private List list;
- *
- * @Test
- * public void shouldDoSomething() {
- * list.add(100);
- * }
- * }
- * <p>
- *
- * </code></pre>
- */
-@Deprecated
-public class MockitoJUnit44Runner extends MockitoJUnitRunner {
-
- public MockitoJUnit44Runner(Class<?> klass) throws InvocationTargetException {
- super(klass);
- }
-}
\ No newline at end of file
diff --git a/src/main/java/org/mockito/stubbing/answers/ReturnsElementsOf.java b/src/main/java/org/mockito/stubbing/answers/ReturnsElementsOf.java
deleted file mode 100644
index bd8f182455..0000000000
--- a/src/main/java/org/mockito/stubbing/answers/ReturnsElementsOf.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * Copyright (c) 2007 Mockito contributors
- * This program is made available under the terms of the MIT License.
- */
-package org.mockito.stubbing.answers;
-
-import java.util.Collection;
-
-/**
- * Returns elements of the collection. Keeps returning the last element forever.
- * Might be useful on occasion when you have a collection of elements to return.
- * <p>
- * <pre class="code"><code class="java">
- * //this:
- * when(mock.foo()).thenReturn(1, 2, 3);
- * //is equivalent to:
- * when(mock.foo()).thenReturn(new ReturnsElementsOf(Arrays.asList(1, 2, 3)));
- * </code></pre>
- *
- * @deprecated Use {@link org.mockito.AdditionalAnswers#returnsElementsOf}
- */
-@Deprecated
-public class ReturnsElementsOf extends org.mockito.internal.stubbing.answers.ReturnsElementsOf {
-
- @Deprecated
- public ReturnsElementsOf(Collection<?> elements) {
- super(elements);
- }
-}
\ No newline at end of file
| diff --git a/src/test/java/org/mockito/runners/RunnersValidateFrameworkUsageTest.java b/src/test/java/org/mockito/runners/RunnersValidateFrameworkUsageTest.java
index 35f29a78d3..44f1de9a06 100644
--- a/src/test/java/org/mockito/runners/RunnersValidateFrameworkUsageTest.java
+++ b/src/test/java/org/mockito/runners/RunnersValidateFrameworkUsageTest.java
@@ -16,7 +16,7 @@
import org.mockito.internal.runners.util.FrameworkUsageValidator;
import org.mockitoutil.TestBase;
-@SuppressWarnings({"unchecked", "deprecation"})
+@SuppressWarnings({"unchecked"})
public class RunnersValidateFrameworkUsageTest extends TestBase {
private Runner runner;
@@ -51,7 +51,7 @@ public void shouldValidateWithDefaultRunner() throws Exception {
@Test
public void shouldValidateWithD44Runner() throws Exception {
//given
- runner = new MockitoJUnit44Runner(DummyTest.class);
+ runner = new MockitoJUnitRunner(DummyTest.class);
//when
runner.run(notifier);
diff --git a/src/test/java/org/mockitousage/junitrunner/JUnit44RunnerTest.java b/src/test/java/org/mockitousage/junitrunner/JUnit44RunnerTest.java
deleted file mode 100644
index cc5e08a451..0000000000
--- a/src/test/java/org/mockitousage/junitrunner/JUnit44RunnerTest.java
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * Copyright (c) 2007 Mockito contributors
- * This program is made available under the terms of the MIT License.
- */
-package org.mockitousage.junitrunner;
-
-import static org.junit.Assert.*;
-import static org.mockito.Mockito.*;
-import static org.mockitousage.junitrunner.Filters.*;
-
-import java.util.List;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.InjectMocks;
-import org.mockito.Mock;
-import org.mockito.runners.MockitoJUnit44Runner;
-
-@RunWith(MockitoJUnit44Runner.class)
-@SuppressWarnings( { "unchecked", "deprecation" })
-public class JUnit44RunnerTest {
-
- @InjectMocks
- private ListDependent listDependent = new ListDependent();
-
- @Mock
- private List list;
-
- @Test
- public void shouldInitMocksUsingRunner() {
- list.add("test");
- verify(list).add("test");
- }
- @Test
- public void shouldInjectMocksUsingRunner() {
- assertSame(list, listDependent.getList());
- }
-
- @Test
- public void shouldFilterTestMethodsCorrectly() throws Exception{
- MockitoJUnit44Runner runner = new MockitoJUnit44Runner(this.getClass());
-
- runner.filter(methodNameContains("shouldInitMocksUsingRunner"));
-
- assertEquals(1, runner.testCount());
- }
-
- class ListDependent {
- private List list;
-
- public List getList() {
- return list;
- }
- }
-}
\ No newline at end of file
diff --git a/src/test/java/org/mockitousage/matchers/CapturingArgumentsTest.java b/src/test/java/org/mockitousage/matchers/CapturingArgumentsTest.java
index 43c362a9b4..9457cd51c5 100644
--- a/src/test/java/org/mockitousage/matchers/CapturingArgumentsTest.java
+++ b/src/test/java/org/mockitousage/matchers/CapturingArgumentsTest.java
@@ -63,7 +63,7 @@ interface EmailService {
@Test
public void should_allow_assertions_on_captured_argument() {
//given
- ArgumentCaptor<Person> argument = new ArgumentCaptor<Person>();
+ ArgumentCaptor<Person> argument = ArgumentCaptor.forClass(Person.class);
//when
bulkEmailService.email(12);
diff --git a/src/test/java/org/mockitousage/stacktrace/PointingStackTraceToActualInvocationTest.java b/src/test/java/org/mockitousage/stacktrace/PointingStackTraceToActualInvocationTest.java
index ea57e5e645..2522224197 100644
--- a/src/test/java/org/mockitousage/stacktrace/PointingStackTraceToActualInvocationTest.java
+++ b/src/test/java/org/mockitousage/stacktrace/PointingStackTraceToActualInvocationTest.java
@@ -12,13 +12,12 @@
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.exceptions.verification.NeverWantedButInvoked;
-import org.mockito.runners.MockitoJUnit44Runner;
+import org.mockito.runners.MockitoJUnitRunner;
import org.mockitousage.IMethods;
import org.mockitoutil.TestBase;
//This is required to make sure stack trace is well filtered when runner is ON
-@SuppressWarnings("deprecation")
-@RunWith(MockitoJUnit44Runner.class)
+@RunWith(MockitoJUnitRunner.class)
public class PointingStackTraceToActualInvocationTest extends TestBase {
@Mock private IMethods mock;
diff --git a/src/test/java/org/mockitousage/stubbing/StubbingWithExtraAnswersTest.java b/src/test/java/org/mockitousage/stubbing/StubbingWithExtraAnswersTest.java
index b85c2394eb..8fb8a89857 100644
--- a/src/test/java/org/mockitousage/stubbing/StubbingWithExtraAnswersTest.java
+++ b/src/test/java/org/mockitousage/stubbing/StubbingWithExtraAnswersTest.java
@@ -11,9 +11,9 @@
import java.util.List;
import org.junit.Test;
+import org.mockito.AdditionalAnswers;
import org.mockito.Mock;
import org.mockito.exceptions.base.MockitoException;
-import org.mockito.stubbing.answers.ReturnsElementsOf;
import org.mockitousage.IMethods;
import org.mockitoutil.TestBase;
@@ -25,7 +25,7 @@ public class StubbingWithExtraAnswersTest extends TestBase {
public void shouldWorkAsStandardMockito() throws Exception {
//when
List<Integer> list = asList(1, 2, 3);
- when(mock.objectReturningMethodNoArgs()).thenAnswer(new ReturnsElementsOf(list));
+ when(mock.objectReturningMethodNoArgs()).thenAnswer(AdditionalAnswers.returnsElementsOf(list));
//then
assertEquals(1, mock.objectReturningMethodNoArgs());
@@ -40,7 +40,7 @@ public void shouldWorkAsStandardMockito() throws Exception {
public void shouldReturnNullIfNecessary() throws Exception {
//when
List<Integer> list = asList(1, null);
- when(mock.objectReturningMethodNoArgs()).thenAnswer(new ReturnsElementsOf(list));
+ when(mock.objectReturningMethodNoArgs()).thenAnswer(AdditionalAnswers.returnsElementsOf(list));
//then
assertEquals(1, mock.objectReturningMethodNoArgs());
@@ -52,7 +52,7 @@ public void shouldReturnNullIfNecessary() throws Exception {
public void shouldScreamWhenNullPassed() throws Exception {
try {
//when
- new ReturnsElementsOf(null);
+ AdditionalAnswers.returnsElementsOf(null);
//then
fail();
} catch (MockitoException e) {}
| train | train | 2016-03-09T16:56:37 | "2016-03-14T12:38:43Z" | ChristianSchwarz | train |
mockito/mockito/407_412 | mockito/mockito | mockito/mockito/407 | mockito/mockito/412 | [
"keyword_pr_to_issue"
] | 8331e6e4bb37e459950dc12ef48ff4f5ed10f953 | 3da645d2d38e6be82bdcd2ee2bb7abf08deb74d9 | [
"This is a bug in [ForwardsInvocations](https://github.com/mockito/mockito/blob/master/src/main/java/org/mockito/internal/stubbing/defaultanswers/ForwardsInvocations.java#L41), as you already investigated the expanded varargs are passed to the delegate.\n\nThe current implementation does this:\n\n```\nresult = delegateMethod.invoke(delegatedObject, arguments);\n```\n\nMockito look for method with the signature `String,int,String,double` for the given arguments (\"baz\",12,\"45\",67.8), but such a method doesn't exists.\n\nTo fix the issue the raw/unexpanded arguments must be used\n\n```\nObject[] rawArguments = ((Invocation)invocation).getRawArguments(); \nresult = delegateMethod.invoke(delegatedObject, rawArguments);\n```\n\nNow Mockito looks for method signature `String,Object[]` which is the var args method you want. Note: It is safe to cast to `Invocation` here cause answers always get a Invocation-Instance passed from `MockHandlerImpl`. \n\nIf I find some time I will send a PR with a fix or you or some one else start to fix it. \n",
"Here is PR. I thought about cast, but may be better pull up method [org.mockito.invocation.Invocation#getRawArguments](https://github.com/mockito/mockito/blob/master/src/main/java/org/mockito/invocation/Invocation.java#L42) to interface [org.mockito.invocation.InvocationOnMock](https://github.com/mockito/mockito/blob/master/src/main/java/org/mockito/invocation/InvocationOnMock.java)?\n",
"@andreyrmg \nPulling `getRawArguments()` up to `InvocationOnMock` would help in this narrow use case. On the other side it bloat the public API and migth confuse clients that implement custom Answer's, which method to choose `getArguments()` or `getRawArguments()`. \n\nWDYT?\n",
"Yes, I agree with you. But I think, this is already a bit confusing that method `getArgument()` returns expanded varargs. Maybe we need two methods `getArguments()` and `getExpandedArguments()`?\n",
"Adding new API or changing existing behaviour need to be discussed with the core-members.\n\nI agree with you, `getArguments()` should return unaltered/not expanded arguments. The current `getArguments()` implementation has also the problem that is can't distinguish an null-vararg argument / `varArgMethod(new Type[]{null})` from an null-varag array / `varArgMethod((Type[])null)`.\n"
] | [
"- Looks good, can you split the test cases (empty array/ non empty array) ?\n- Can you also add a test for `invocationOf(Foo.class, \"bar\", \"baz\", new Object[] {null})` and `invocationOf(Foo.class, \"bar\", \"baz\", null)` \n- Would you mind using AssertJ's Assertions.assertThat(..).is(..), it is more readable IMHO?\n",
"There is no need to extend from `TestBase`, right?\n"
] | "2016-05-17T11:18:32Z" | [] | Vararg method call on mock object fails when used org.mockito.AdditionalAnswers#delegatesTo | I try to mock interface with varargs method and default implementation in final class and get this error:
```
java.lang.IllegalArgumentException: wrong number of arguments
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.mockito.internal.stubbing.defaultanswers.ForwardsInvocations.answer(ForwardsInvocations.java:31)
at org.mockito.internal.handler.MockHandlerImpl.handle(MockHandlerImpl.java:93)
at org.mockito.internal.handler.NullResultGuardian.handle(NullResultGuardian.java:29)
at org.mockito.internal.handler.InvocationNotifierHandler.handle(InvocationNotifierHandler.java:38)
at org.mockito.internal.creation.MethodInterceptorFilter.intercept(MethodInterceptorFilter.java:51)
```
I run the following code:
``` java
public class DefaultAnswerDemo {
public interface Foo {
void bar(String baz, Object... args);
}
public static final class FooImpl implements Foo {
@Override
public void bar(String baz, Object... args) {
System.out.println("bar");
}
}
@Test
public void defaultAnswerTest() {
Foo fooImpl = new FooImpl();
Foo foo = mock(Foo.class, withSettings()
.defaultAnswer(delegatesTo(fooImpl)));
foo.bar("baz", 12, "45", 67.8);
}
}
```
This is happens because org.mockito.internal.invocation.InvocationImpl by default expands varargs arguments to flat list. And I have no idea, how correctly fix this.
| [
"src/main/java/org/mockito/internal/stubbing/defaultanswers/ForwardsInvocations.java"
] | [
"src/main/java/org/mockito/internal/stubbing/defaultanswers/ForwardsInvocations.java"
] | [
"src/test/java/org/mockito/internal/stubbing/defaultanswers/ForwardsInvocationsTest.java",
"src/test/java/org/mockitousage/stubbing/StubbingWithDelegateVarArgsTest.java"
] | diff --git a/src/main/java/org/mockito/internal/stubbing/defaultanswers/ForwardsInvocations.java b/src/main/java/org/mockito/internal/stubbing/defaultanswers/ForwardsInvocations.java
index 1916a62ce2..95da223adf 100644
--- a/src/main/java/org/mockito/internal/stubbing/defaultanswers/ForwardsInvocations.java
+++ b/src/main/java/org/mockito/internal/stubbing/defaultanswers/ForwardsInvocations.java
@@ -9,6 +9,7 @@
import java.lang.reflect.Method;
import org.mockito.exceptions.Reporter;
+import org.mockito.invocation.Invocation;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
@@ -37,8 +38,9 @@ public Object answer(InvocationOnMock invocation) throws Throwable {
if (!compatibleReturnTypes(mockMethod.getReturnType(), delegateMethod.getReturnType())) {
new Reporter().delegatedMethodHasWrongReturnType(mockMethod, delegateMethod, invocation.getMock(), delegatedObject);
}
-
- result = delegateMethod.invoke(delegatedObject, invocation.getArguments());
+
+ Object[] rawArguments = ((Invocation) invocation).getRawArguments();
+ result = delegateMethod.invoke(delegatedObject, rawArguments);
} catch (NoSuchMethodException e) {
new Reporter().delegatedMethodDoesNotExistOnDelegate(mockMethod, invocation.getMock(), delegatedObject);
} catch (InvocationTargetException e) {
| diff --git a/src/test/java/org/mockito/internal/stubbing/defaultanswers/ForwardsInvocationsTest.java b/src/test/java/org/mockito/internal/stubbing/defaultanswers/ForwardsInvocationsTest.java
new file mode 100644
index 0000000000..42234edc08
--- /dev/null
+++ b/src/test/java/org/mockito/internal/stubbing/defaultanswers/ForwardsInvocationsTest.java
@@ -0,0 +1,30 @@
+package org.mockito.internal.stubbing.defaultanswers;
+
+import org.junit.Test;
+import org.mockitoutil.TestBase;
+
+public class ForwardsInvocationsTest extends TestBase {
+
+ interface Foo {
+ int bar(String baz, Object... args);
+ }
+
+ private static final class FooImpl implements Foo {
+ @Override
+ public int bar(String baz, Object... args) {
+ return baz.length() + args.length;
+ }
+ }
+
+ @Test
+ public void should_call_method_with_varargs() throws Throwable {
+ ForwardsInvocations forwardsInvocations = new ForwardsInvocations(new FooImpl());
+ assertEquals(4, forwardsInvocations.answer(invocationOf(Foo.class, "bar", "b", new Object[] {12, "3", 4.5})));
+ }
+
+ @Test
+ public void should_call_method_with_empty_varargs() throws Throwable {
+ ForwardsInvocations forwardsInvocations = new ForwardsInvocations(new FooImpl());
+ assertEquals(1, forwardsInvocations.answer(invocationOf(Foo.class, "bar", "b", new Object[] {})));
+ }
+}
\ No newline at end of file
diff --git a/src/test/java/org/mockitousage/stubbing/StubbingWithDelegateVarArgsTest.java b/src/test/java/org/mockitousage/stubbing/StubbingWithDelegateVarArgsTest.java
new file mode 100644
index 0000000000..5f41d7178a
--- /dev/null
+++ b/src/test/java/org/mockitousage/stubbing/StubbingWithDelegateVarArgsTest.java
@@ -0,0 +1,46 @@
+package org.mockitousage.stubbing;
+
+import org.junit.Test;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.AdditionalAnswers.delegatesTo;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.withSettings;
+
+public class StubbingWithDelegateVarArgsTest {
+
+ public interface Foo {
+ int bar(String baz, Object... args);
+ }
+
+ private static final class FooImpl implements Foo {
+
+ @Override
+ public int bar(String baz, Object... args) {
+ return args != null ? args.length : -1; // simple return argument count
+ }
+
+ }
+
+ @Test
+ public void should_not_fail_when_calling_varargs_method() {
+ Foo foo = mock(Foo.class, withSettings()
+ .defaultAnswer(delegatesTo(new FooImpl())));
+ assertThat(foo.bar("baz", 12, "45", 67.8)).isEqualTo(3);
+ }
+
+ @Test
+ public void should_not_fail_when_calling_varargs_method_without_arguments() {
+ Foo foo = mock(Foo.class, withSettings()
+ .defaultAnswer(delegatesTo(new FooImpl())));
+ assertThat(foo.bar("baz")).isEqualTo(0);
+ assertThat(foo.bar("baz", new Object[0])).isEqualTo(0);
+ }
+
+ @Test
+ public void should_not_fail_when_calling_varargs_method_with_null_argument() {
+ Foo foo = mock(Foo.class, withSettings()
+ .defaultAnswer(delegatesTo(new FooImpl())));
+ assertThat(foo.bar("baz", (Object[]) null)).isEqualTo(-1);
+ }
+}
| train | train | 2016-05-17T22:34:52 | "2016-05-03T07:27:24Z" | iam-afk | train |
mockito/mockito/422_423 | mockito/mockito | mockito/mockito/422 | mockito/mockito/423 | [
"timestamp(timedelta=33028.0, similarity=0.8599980107043)"
] | 74e312b7a9236a43eb543bd3184607b75375bc40 | d528d12806a460dd1a646e49afc09dab3cc1c8fe | [
"Hi! Why would you even want to do that? It sounds like a absolutely terrible idea to do that. Can you provide some use case?\n",
"Thank you for the fast reply!\nI need to test that a class behaves in different ways if the log level is debug or not and so I need to mock the logger. If debug is enabled my class will do some heavy computation. The logger is fetched with the classic SLF4J API `LogFactory.getLog(ClassToTest.class)`.\n\nI can use powermock to mock `LogFactory.getLog` but things get quite complicated quite fast since this is invoked only once when the class is loaded. A cleaner solution would be to set the mock logger before the test.\n\nI am working on a low level logging API so I cannot rely on dependency injection.\n",
"@andreicristianpetcu I think setter injection would be better and cleaner. In your test, you set the logger via this method. In your default behavior you only set it in your constructor.\n",
"Loggers are per class and not per instance. If I make my log field not a static final field SonarQube starts to complain. I can add a false positive to SonarQube but the rest of the company uses this behavior.\n",
"Well you have two options:\n1. Make the setter static too. In your `@Before` set the logger to your mock, but storing the original logger. In `@After` set the logger back to the original logger.\n2. Deal with the deficiency of SonarQube and make this an exception. It is a tool to assist you during development, but not a holy grail imo.\n",
"I know that SonarQube is not a holy grail but I cannot change the SonarQube settings.\nWould you refuse a pull request adding this feature? I imagine it is quite small.\n",
"Another solution is to wrap the logger in a class that you can inject. \n\n```\nclass LoggerProxy {\n\n private static final Logger log ....\n\n void debug(...) { log.debug(...); }\n void info(...) { log.info(...); }\n\n}\n```\n\nand then in your class you can call\n\n```\nclass YourClass {\n private final LoggerProxy proxy;\n\n YourClass(LoggerProxy proxy) {\n this.proxy = proxy;\n }\n\n void someMethod() {\n loggerProxy.debug(...); // <-- this you can stub\n }\n}\n```\n\nI'd vote strongly against such a feature as allowing to set private final static fields. But that's just my vote ;) \n\nAnd then everybody's happy! You have cleaner code, Sonar is not violated - life's beautiful :)\n",
"I don't feel comfortable to write code specially to make my code testable.\n\nBelieve me I tried all possible options. I think setting the LOG field using reflection is the simplest. Right now we do it with a class who's purpose is to only set this field in several places. The only two options that I have:\n- use this class;\n- add the feature to upstream (in this case Mockito).\n\nIf you would not accept such a feature I will not add it but I think it adds value. I think setting private instance fields using reflection as it is currently implemented in Mockito is a bad practice but I use it anyway since there are some really rare cases where this is the best option. Setting private static final fields is the same as setting private instance fields: bad practice but needed from time to time.\n",
"Normally you shouldn't actually verify if stuff has been logged. If that's so important to you then IMO you should use good practices to achieve that solution. Maybe @bric3 or @szczepiq has some other opinion on this but I don't think that allowing more hacks to test a logger without injecting it through a constructor is a good idea. \n",
"I understand you will not use this feature, but do you consider it harmful?\n[Here is a StackOverflow](http://stackoverflow.com/a/2474242/1387563) solution for setting private static final field and I want to implement it the same way.\n",
"I consider it allowing people write bad code. But that's only my opinion.\nIf others feel that this is a good feature to add then I'm not going to\nobject.\n",
"I have to side with @marcingrzejszczak here. Adding this functionality will likely result in bad code because the production code is not testable. I do not see making code testable as a problem.\n",
"Ok then. I'll try to make a pull request tonight and I hope it gets accepted :)\n",
"So I can assume that we can close this\n",
"> Hi! Why would you even want to do that? It sounds like a absolutely terrible idea to do that. Can you provide some use case?\r\n\r\nCould you please explain to me why using a static class variable is a terrible idea?",
"> I need to test that a class behaves in different ways if the log level is debug or not and so I need to mock the logger.\r\n\r\nIn this situation, you would set the logger's logging level to DEBUG from your logging framework, rather than mocking the logger. For example in Logback:\r\n\r\n```\r\nLoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();\r\nch.qos.logback.classic.Logger logger = loggerContext.getLogger(fullyQualifiedClassName);\r\nlogger.setLevel(Level.toLevel(logLevel));\r\n```"
] | [] | "2016-05-31T18:51:04Z" | [
"on hold"
] | Whitebox.setInternalState for private static final fields | Hello,
Can you please add the ability for [Whitebox.setInternalState](https://github.com/mockito/mockito/blob/74e312b7a9236a43eb543bd3184607b75375bc40/src/main/java/org/mockito/internal/util/reflection/Whitebox.java#L22-L31) to be invokable on classes with private static final field?
``` java
Whitebox.setInternalState(ClassToTest.class, "LOG", mockLog);
```
I did not understand where is the best place to add a feature request. I hope this is the best place.
Thank you
| [
"src/main/java/org/mockito/internal/util/reflection/Whitebox.java"
] | [
"src/main/java/org/mockito/internal/util/reflection/Whitebox.java"
] | [
"src/test/java/org/mockito/internal/util/reflection/DummyParentClassForTests.java",
"src/test/java/org/mockito/internal/util/reflection/WhiteboxTest.java"
] | diff --git a/src/main/java/org/mockito/internal/util/reflection/Whitebox.java b/src/main/java/org/mockito/internal/util/reflection/Whitebox.java
index c63f59b87a..14ea30be98 100644
--- a/src/main/java/org/mockito/internal/util/reflection/Whitebox.java
+++ b/src/main/java/org/mockito/internal/util/reflection/Whitebox.java
@@ -5,31 +5,58 @@
package org.mockito.internal.util.reflection;
import java.lang.reflect.Field;
+import java.lang.reflect.Modifier;
public class Whitebox {
- public static Object getInternalState(Object target, String field) {
- Class<?> c = target.getClass();
+ public static Object getInternalState(Object targetInstance, String fieldName) {
+ return getInternalState(targetInstance.getClass(), targetInstance, fieldName);
+ }
+
+ public static Object getInternalState(Class targetClass, String fieldName) {
+ return getInternalState(targetClass, null, fieldName);
+ }
+
+ private static Object getInternalState(Class<?> targetClass, Object targetInstance, String fieldName) {
try {
- Field f = getFieldFromHierarchy(c, field);
+ Field f = getFieldFromHierarchy(targetClass, fieldName);
f.setAccessible(true);
- return f.get(target);
+ return f.get(targetInstance);
} catch (Exception e) {
throw new RuntimeException("Unable to get internal state on a private field. Please report to mockito mailing list.", e);
}
}
- public static void setInternalState(Object target, String field, Object value) {
- Class<?> c = target.getClass();
+ public static void setInternalState(Object targetInstance, String fieldName, Object value) {
+ setInternalState(targetInstance.getClass(), targetInstance, fieldName, value);
+ }
+
+ public static void setInternalState(Class targetClass, String fieldName, Object value) {
+ setInternalState(targetClass, null, fieldName, value);
+ }
+
+ private static void setInternalState(Class targetClass, Object targetInstance, String fieldName, Object value) {
try {
- Field f = getFieldFromHierarchy(c, field);
+ Field f = getFieldFromHierarchy(targetClass, fieldName);
f.setAccessible(true);
- f.set(target, value);
+ removeFinalModifierIfPresent(f);
+ f.set(targetInstance, value);
} catch (Exception e) {
throw new RuntimeException("Unable to set internal state on a private field. Please report to mockito mailing list.", e);
}
}
+ private static void removeFinalModifierIfPresent(Field fieldToRemoveFinalFrom) throws IllegalAccessException, NoSuchFieldException {
+ int fieldModifiersMask = fieldToRemoveFinalFrom.getModifiers();
+ boolean isFinalModifierPresent = (fieldModifiersMask & Modifier.FINAL) == Modifier.FINAL;
+ if (isFinalModifierPresent) {
+ Field modifiersField = Field.class.getDeclaredField("modifiers");
+ modifiersField.setAccessible(true);
+ int fieldModifiersMaskWithoutFinal = fieldModifiersMask & ~Modifier.FINAL;
+ modifiersField.setInt(fieldToRemoveFinalFrom, fieldModifiersMaskWithoutFinal);
+ }
+ }
+
private static Field getFieldFromHierarchy(Class<?> clazz, String field) {
Field f = getField(clazz, field);
while (f == null && clazz != Object.class) {
| diff --git a/src/test/java/org/mockito/internal/util/reflection/DummyParentClassForTests.java b/src/test/java/org/mockito/internal/util/reflection/DummyParentClassForTests.java
index 6967c02c8a..2b5da62228 100644
--- a/src/test/java/org/mockito/internal/util/reflection/DummyParentClassForTests.java
+++ b/src/test/java/org/mockito/internal/util/reflection/DummyParentClassForTests.java
@@ -4,8 +4,13 @@
*/
package org.mockito.internal.util.reflection;
+import java.util.logging.Logger;
+
public class DummyParentClassForTests {
+ @SuppressWarnings("unused")//I know, I know. We're doing nasty reflection hacks here...
+ private static final Logger LOG = Logger.getLogger(DummyParentClassForTests.class.toString());
+
@SuppressWarnings("unused")//I know, I know. We're doing nasty reflection hacks here...
private String somePrivateField;
}
diff --git a/src/test/java/org/mockito/internal/util/reflection/WhiteboxTest.java b/src/test/java/org/mockito/internal/util/reflection/WhiteboxTest.java
index add464c140..97a07ea530 100644
--- a/src/test/java/org/mockito/internal/util/reflection/WhiteboxTest.java
+++ b/src/test/java/org/mockito/internal/util/reflection/WhiteboxTest.java
@@ -5,10 +5,16 @@
package org.mockito.internal.util.reflection;
import org.junit.Test;
+import org.mockito.Mock;
import org.mockitoutil.TestBase;
+import java.util.logging.Logger;
+
public class WhiteboxTest extends TestBase {
+ @Mock
+ Logger mockLogger;
+
@Test
public void private_state() {
//given
@@ -19,4 +25,13 @@ public void private_state() {
Object internalState = Whitebox.getInternalState(dummy, "somePrivateField");
assertEquals("cool!", internalState);
}
+
+ @Test
+ public void private_static_final_state() {
+ //when
+ Whitebox.setInternalState(DummyParentClassForTests.class, "LOG", mockLogger);
+ //then
+ Object internalState = Whitebox.getInternalState(DummyParentClassForTests.class, "LOG");
+ assertEquals(mockLogger, internalState);
+ }
}
\ No newline at end of file
| test | train | 2016-05-27T20:52:55 | "2016-05-31T10:59:45Z" | andreicristianpetcu | train |
mockito/mockito/426_432 | mockito/mockito | mockito/mockito/426 | mockito/mockito/432 | [
"keyword_pr_to_issue"
] | a1de9a5e1d38774f2f3e343e60c56e8f000b71ca | 3c4edc6b49ce4a30dcaf00a78cf014c245f2eefa | [
"@raphw thanks for merging the PR that fast! Would you mind reopening this ticket? There are more classes that can be refactored that way, I would like to extend the list.\n",
"Big :+1: for me btw, but please keep the pull requests managable and as small as possible. Preferably refactoring 1 method at a time. That way it is a lot easier to review.\n",
"I agree, there is nothing wrong with multiple PRs, the quick merge is a reaction to an easy overview (and being stuck at an Ukrainian airport without access to the Eurocup).\n",
"There are still two unit tests failing, could you have a look @ChristianSchwarz - I just had a quick look and there are two unit tests failing which seems related to the way you refactored the previous stubbing of the `Reporter`.\n\nI should have checked more thoroughly before merging, hopefully you can fix the problem soon. Alternatively, I will just rollback the one commit (the first one is good) and we can reapply the patch once you fixed the two unit tests. Thank you, really, this was great clean-up.\n",
"I fixed the one test error. I push it tonight.\n\nPS: I also fixed a bug in the stack trace cleaner. Not a biggy but please do not `@Ignore` tests. Especially in big commits, it is easy to miss that single annotation.\n",
"@raphw Which test(s) is/are failing? I will fix it asap! Too bad that some test fail on a regulare base, is it possible to ignore them in the ide only?\n",
"You can see the build output here: https://travis-ci.org/mockito/mockito#L254-L269\n\nI advise you to run the tests with `./gradlew build`. This should work.\n",
"@TimvdLippe know what you mean! The next PR's include only one refactored class at a time.\n",
"I have it all fixed on local but I did not have access to wifi without 22 blocked. Will commit soon.\n",
"@raphw can you please reopen this issue \n",
"Sorry, GitHub automatically closes issues that reference a PR.\n",
"@ChristianSchwarz If a commit contains a comment like \"Fixes #426\" the mentioned issue is automatically closed by github.\n",
"@PascalSchumacher Good to know! I will leave it out for the upcoming PR's. Thanks!\n",
"Now that we are pulling in static methods, I would like to propose a new (linter) rule. To make it easier to read a file, I would like that all methods invoked in the current class are referenced with `this.` (and `super.` for that matter). Therefore if we see `this.verify`, we know it is in the current class and the same object, whereas `verify` references a static method in this class, or an imported static method. Do you agree @mockito/developers ?\n",
"> I would like that all methods invoked in the current class are referenced with this. (and super. for that matter).\n\nTo me it feels like unnecessary/duplicate code cause `this` is implicit. Adding `this.` before every instance call would create a lot more text and would IMHO reduce readability. E.g.:\n\n`this.doSometing(this.withPrivateMethod())` vs. `doSomething(withPrivateMethod())`\n\n> Therefore if we see this.verify, we know it is in the current class and the same object, whereas verify references a static method in this class, or an imported static method.\n\nAn other option avoid ambiguity is to qualify static methods via its class name. This way you can also distinguish which verify(..) is called ( `MockitoCore.verify(..)` / `Mocktio.verify(..)`) , which is not an easy task when a static import is used.\n",
"I'm not coding too much in Mockito ATM (hopefully now after SpringOne conference I'll have more time) but I fully agree with @ChristianSchwarz . IMO the best solution is to: \n- omit `this` before method calls. \n- if necessary provide the class for static method call\n",
"Respectful -1\n\nI like when the class formally declares collaborators instead of calling out to static methods. This makes it easy to reason about the code. I don't need to read every line of code in the class to find out external couplings realized via static methods. I can see the couplings via fields, I can easily query how the field variable is used, etc. Another use case is when we discover missing/incorrect unit test coverage (or we do some larger refactorings) and we cannot easily write tests because code is too procedural.\n\nThe benefits for converting to static utilities have minimal significance to me. Yet, there is a downside I care about (e.g. maintainability of procedural code, static methods that consume static methods, that consume static methods...).\n\nHence, I down vote this sort of changes. Going down this path, all stateless classes in Mockito would become static utilities :)\n\nYou can get +1's from other maintainers and have your changes merged - I'm not here to block your changes but to give honest feedback. I see merit in arguments for static utilities. They do not outweigh the cost in my opinion.\n",
"I'm mitigated about this as well. I understand well that mockito creates garbage, but they are short lived and **most probably** won't go in the old generation especially in the test phase. Yet the faster the tests are the more developers will run them, it **may** have impacts on big projects. Also design wise I don't like much static methods too.\n\nHowever I don't totally agree with the above points : \n\n> I don't need to read every line of code in the class to find out external couplings realized via static methods. I can see the couplings via fields, I can easily query how the field variable is used, etc.\n\nCoupling appears also in the import section ; static methods are visible there. And modern IDE usually highlight this. IntelliJ even have a warning if import section is too big, just as there's warning if there's too many fields. This point should not be the reason to avoid static methods.\n\n> maintainability of procedural code, static methods that consume static methods, that consume static methods...\n\nHaving instance methods does not protect again procedural code.\n\n---\n\nI believe there's middle ground there : \n- Mockito project contains a lot of small utility stateless objects that are supporting mockito features, these are usually collections tools, reflection tools, those could are good candidate for static methods. Objects like `FieldSetter`, `FieldCopier`, `LenientCopyTool` could be nice candidate for static methods\n- Mockito features could be backed by object instances. Objects like `MockitoCore`, `MockCreationValidator`, `ArgumentMatchingTool` are candidate to stay objects.\n",
"Exactly the middle ground described by Brice is my motivation for merging most of the PRs. This is also the reason I have not yet merged the MockitoCore PR for this exact reason.\n\nIf an object is not a attribute or parameter, but an internal creation and immediately dismissed, I value a pure function more.\n",
"Thought: when we switch to Java 8, we can use interfaces with default\nmethods. The switch from static utility to interface is very easy now (just\na couple of text replaces, no method reference modifications).\n\nOn Fri, 12 Aug 2016, 17:23 Brice Dutheil, notifications@github.com wrote:\n\n> I'm mitigated about this as well. I understand well that mockito creates\n> garbage, but they are short lived and _most probably_ won't go in the old\n> generation especially in the test phase. Yet the faster the tests are the\n> more developers will run them, it _may_ have impacts on big projects.\n> Also design wise I don't like much static methods too.\n> \n> However I don't totally agree with the above points :\n> \n> I don't need to read every line of code in the class to find out external\n> couplings realized via static methods. I can see the couplings via fields,\n> I can easily query how the field variable is used, etc.\n> \n> Coupling appears also in the import section ; static methods are visible\n> there. And modern IDE usually highlight this. IntelliJ even have a warning\n> if import section is too big, just as there's warning if there's too many\n> fields. This point should not be the reason to avoid static methods.\n> \n> maintainability of procedural code, static methods that consume static\n> methods, that consume static methods...\n> \n> ## Having instance methods does not protect again procedural code.\n> \n> I believe there's middle ground there :\n> \n> -\n> \n> Mockito project contains a lot of small utility stateless objects that\n> are supporting mockito features, these are usually collections tools,\n> reflection tools, those could are good candidate for static methods.\n> Objects like FieldSetter, FieldCopier, LenientCopyTool could be nice\n> candidate for static methods\n> -\n> \n> Mockito features could be backed by object instances. Objects like\n> MockitoCore, MockCreationValidator, ArgumentMatchingTool are candidate\n> to stay objects.\n> \n> —\n> You are receiving this because you modified the open/close state.\n> Reply to this email directly, view it on GitHub\n> https://github.com/mockito/mockito/issues/426#issuecomment-239476519,\n> or mute the thread\n> https://github.com/notifications/unsubscribe-auth/AFrDb6QVlVesWgPAhurimgSUPQTRcTZSks5qfJALgaJpZM4IzjKm\n> .\n",
"This feels like a misuse of the default methods.\n",
"I think you mean static-methods in interfaces here? Default-methods require an instance to be called on.\nAnyway I don't think that it is a good idea. It would a result in an interface that is not intended to be implemented or extended and only serves as container for utility methods. IMHO a class with private constructor is the best construct to do this.\n",
"> > Thought: when we switch to Java 8, we can use interfaces with default\n> > methods.\n> \n> Default-methods require an instance to be called on.\n\nI was thinking exactly that, default methods in the interface plus instance (either as a separate file or as a singleton declared within the interface).\n",
"@ChristianSchwarz What do you think to continue the work here with the middle ground described [here](https://github.com/mockito/mockito/issues/426#issuecomment-239476519) ?\n",
"I am attempting to refactor the MatcherBinder class to a static utility class and am having trouble refactoring the following from MockHandlerImplTest.java: `\r\nhandler.matchersBinder = new MatchersBinder() {\r\n public InvocationMatcher bindMatchers(ArgumentMatcherStorage argumentMatcherStorage, Invocation invocation) {\r\n throw new InvalidUseOfMatchersException();\r\n }\r\n}; `\r\nHow can I maintain the abstract class definition when I am not able to create an object of MatcherBinder?\r\n\r\nAny help is appreciated! ",
"Let's close this ticket. Refactorings can be done as needed as we work with the code."
] | [
"Formatting again?\n",
"?\n",
"I added a new line in order to trigger a new build. The concurrent test are failing on every 2nd run.\n",
"tab vs. 4x space , fixed...\n"
] | "2016-06-15T13:05:28Z" | [] | Refactor instance based utility classes to static utility classes | The internal implementation of Mockito contains numerous helper classed that serve as a container for useful methods. By its nature these classes don't have a state. Currently some them are instance based in other word you need to create the utility class to call a helper method. This not only pollutes the heap but also the code cause instance methods can't be imported statically.
Here is an example:
```java
Helper helper = new Helper();
if (helper.isInputValid(input)){
[...]
}
```
vs. static import of Helper.isInputValid
```java
if (isInputValid(input)){
[...]
}
```
The aim of this ticket is to identify canidates that can be refactored to static utility classes. If you like to refactoring and mockito feel free to send a PR and reference this issue.
Refactoring canidates:
- [ ] `AccessibilityChanger`
- [ ] `BeanPropertySetter`
- [ ] `ConditionalStackTraceFilter`
- [ ] `FieldCopier`
- [ ] `FieldReader`
- [ ] `GenericMaster` should be integrate into `GenericTypeResolver`
- [ ] `JUnitFailureHacker` can be removed when the deprecated `VerboseMockitoJUnitRunner` is removed
- [ ] `LenientCopyTool`
- [ ] `MatcherBinder`
- [ ] `MockitoCore` should better be a singleton
- [x] `MockCreationValidator`
- [ ] `RemoveFirstLine`
- [x] #591 `ArgumentMatchingTool`
- [x] #515 `AllInvocationsFinder`
- [x] #502 `ArgumentsComparator`
- [x] #540 `ArrayUtils`
- [x] #490 `AtLeastXNumberOfInvocationsChecker`
- [x] #490 `AtLeastXNumberOfInvocationsInOrderChecker`
- [ ] #912 `Constructors`
- [x] #427 `FieldSetter`
- [x] #908 `FriendlyExceptionMaker`
- [x] #431 `HandyReturnValues`
- [x] #432 `InvocationMarker`
- [x] #462 `InvocationsFinder`
- [x] #908 `JUnitDetecter`
- [x] #490 `MissingInvocationChecker`
- [x] #490 `MissingInvocationInOrderChecker`
- [x] #514 `MockUtil`
- [x] #503 `NonGreedyNumberOfInvocationsInOrderChecker`
- [x] #907 `NumberOfInvocationsInOrderChecker`
- [x] #907 `NumberOfInvocationsChecker`
- [x] #547 `ObjectMethodsGuru`
- [x] #427 `Reporter`
- [x] #535 `SuperTypesLastSorter`
- [x] #501 `TestMethodFinder`
- [x] #515 `VerifiableInvocationsFinder`
| [
"src/main/java/org/mockito/internal/invocation/InvocationMarker.java",
"src/main/java/org/mockito/internal/verification/AtMost.java",
"src/main/java/org/mockito/internal/verification/Only.java",
"src/main/java/org/mockito/internal/verification/checkers/AtLeastXNumberOfInvocationsChecker.java",
"src/main/java/org/mockito/internal/verification/checkers/AtLeastXNumberOfInvocationsInOrderChecker.java",
"src/main/java/org/mockito/internal/verification/checkers/NonGreedyNumberOfInvocationsInOrderChecker.java",
"src/main/java/org/mockito/internal/verification/checkers/NumberOfInvocationsChecker.java",
"src/main/java/org/mockito/internal/verification/checkers/NumberOfInvocationsInOrderChecker.java"
] | [
"src/main/java/org/mockito/internal/invocation/InvocationMarker.java",
"src/main/java/org/mockito/internal/verification/AtMost.java",
"src/main/java/org/mockito/internal/verification/Only.java",
"src/main/java/org/mockito/internal/verification/checkers/AtLeastXNumberOfInvocationsChecker.java",
"src/main/java/org/mockito/internal/verification/checkers/AtLeastXNumberOfInvocationsInOrderChecker.java",
"src/main/java/org/mockito/internal/verification/checkers/NonGreedyNumberOfInvocationsInOrderChecker.java",
"src/main/java/org/mockito/internal/verification/checkers/NumberOfInvocationsChecker.java",
"src/main/java/org/mockito/internal/verification/checkers/NumberOfInvocationsInOrderChecker.java"
] | [
"src/test/java/org/mockito/internal/invocation/InvocationMarkerTest.java",
"src/test/java/org/mockito/internal/verification/checkers/AtLeastXNumberOfInvocationsCheckerTest.java"
] | diff --git a/src/main/java/org/mockito/internal/invocation/InvocationMarker.java b/src/main/java/org/mockito/internal/invocation/InvocationMarker.java
index 882ccf2681..f05a22158b 100644
--- a/src/main/java/org/mockito/internal/invocation/InvocationMarker.java
+++ b/src/main/java/org/mockito/internal/invocation/InvocationMarker.java
@@ -11,22 +11,24 @@
public class InvocationMarker {
- public void markVerified(List<Invocation> invocations, CapturesArgumentsFromInvocation wanted) {
+ private InvocationMarker(){}
+
+ public static void markVerified(List<Invocation> invocations, CapturesArgumentsFromInvocation wanted) {
for (Invocation invocation : invocations) {
markVerified(invocation, wanted);
}
}
- public void markVerified(Invocation invocation, CapturesArgumentsFromInvocation wanted) {
+ public static void markVerified(Invocation invocation, CapturesArgumentsFromInvocation wanted) {
invocation.markVerified();
wanted.captureArgumentsFrom(invocation);
}
- public void markVerifiedInOrder(List<Invocation> chunk, CapturesArgumentsFromInvocation wanted, InOrderContext context) {
+ public static void markVerifiedInOrder(List<Invocation> chunk, CapturesArgumentsFromInvocation wanted, InOrderContext context) {
markVerified(chunk, wanted);
for (Invocation i : chunk) {
context.markVerified(i);
}
}
-}
+}
\ No newline at end of file
diff --git a/src/main/java/org/mockito/internal/verification/AtMost.java b/src/main/java/org/mockito/internal/verification/AtMost.java
index 8b5e0eeef9..a47c832949 100644
--- a/src/main/java/org/mockito/internal/verification/AtMost.java
+++ b/src/main/java/org/mockito/internal/verification/AtMost.java
@@ -6,14 +6,13 @@
package org.mockito.internal.verification;
import static org.mockito.exceptions.Reporter.wantedAtMostX;
+import static org.mockito.internal.invocation.InvocationMarker.markVerified;
import java.util.Iterator;
import java.util.List;
-import org.mockito.exceptions.Reporter;
import org.mockito.exceptions.base.MockitoException;
import org.mockito.internal.invocation.InvocationMatcher;
-import org.mockito.internal.invocation.InvocationMarker;
import org.mockito.internal.invocation.InvocationsFinder;
import org.mockito.internal.verification.api.VerificationData;
import org.mockito.invocation.Invocation;
@@ -22,7 +21,6 @@
public class AtMost implements VerificationMode {
private final int maxNumberOfInvocations;
- private final InvocationMarker invocationMarker = new InvocationMarker();
public AtMost(int maxNumberOfInvocations) {
if (maxNumberOfInvocations < 0) {
@@ -43,7 +41,7 @@ public void verify(VerificationData data) {
}
removeAlreadyVerified(found);
- invocationMarker.markVerified(found, wanted);
+ markVerified(found, wanted);
}
@Override
diff --git a/src/main/java/org/mockito/internal/verification/Only.java b/src/main/java/org/mockito/internal/verification/Only.java
index 04b4bdbfcc..cf7febb8aa 100644
--- a/src/main/java/org/mockito/internal/verification/Only.java
+++ b/src/main/java/org/mockito/internal/verification/Only.java
@@ -6,10 +6,10 @@
import static org.mockito.exceptions.Reporter.noMoreInteractionsWanted;
import static org.mockito.exceptions.Reporter.wantedButNotInvoked;
+import static org.mockito.internal.invocation.InvocationMarker.markVerified;
import java.util.List;
-import org.mockito.internal.invocation.InvocationMarker;
import org.mockito.internal.invocation.InvocationMatcher;
import org.mockito.internal.invocation.InvocationsFinder;
import org.mockito.internal.verification.api.VerificationData;
@@ -19,7 +19,6 @@
public class Only implements VerificationMode {
private final InvocationsFinder finder = new InvocationsFinder();
- private final InvocationMarker marker = new InvocationMarker();
@SuppressWarnings("unchecked")
public void verify(VerificationData data) {
@@ -33,7 +32,7 @@ public void verify(VerificationData data) {
if (invocations.size() != 1 || chunk.size() == 0) {
throw wantedButNotInvoked(wantedMatcher);
}
- marker.markVerified(chunk.get(0), wantedMatcher);
+ markVerified(chunk.get(0), wantedMatcher);
}
public VerificationMode description(String description) {
diff --git a/src/main/java/org/mockito/internal/verification/checkers/AtLeastXNumberOfInvocationsChecker.java b/src/main/java/org/mockito/internal/verification/checkers/AtLeastXNumberOfInvocationsChecker.java
index 4eadb22e85..4a9e5dca7e 100644
--- a/src/main/java/org/mockito/internal/verification/checkers/AtLeastXNumberOfInvocationsChecker.java
+++ b/src/main/java/org/mockito/internal/verification/checkers/AtLeastXNumberOfInvocationsChecker.java
@@ -6,10 +6,10 @@
package org.mockito.internal.verification.checkers;
import static org.mockito.exceptions.Reporter.tooLittleActualInvocations;
+import static org.mockito.internal.invocation.InvocationMarker.markVerified;
import java.util.List;
-import org.mockito.internal.invocation.InvocationMarker;
import org.mockito.internal.invocation.InvocationMatcher;
import org.mockito.internal.invocation.InvocationsFinder;
import org.mockito.invocation.Invocation;
@@ -18,7 +18,6 @@
public class AtLeastXNumberOfInvocationsChecker {
InvocationsFinder finder = new InvocationsFinder();
- InvocationMarker invocationMarker = new InvocationMarker();
public void check(List<Invocation> invocations, InvocationMatcher wanted, int wantedCount) {
List<Invocation> actualInvocations = finder.findInvocations(invocations, wanted);
@@ -29,6 +28,6 @@ public void check(List<Invocation> invocations, InvocationMatcher wanted, int wa
throw tooLittleActualInvocations(new AtLeastDiscrepancy(wantedCount, actualCount), wanted, lastLocation);
}
- invocationMarker.markVerified(actualInvocations, wanted);
+ markVerified(actualInvocations, wanted);
}
}
\ No newline at end of file
diff --git a/src/main/java/org/mockito/internal/verification/checkers/AtLeastXNumberOfInvocationsInOrderChecker.java b/src/main/java/org/mockito/internal/verification/checkers/AtLeastXNumberOfInvocationsInOrderChecker.java
index c3d7f93cbb..96c61dc43d 100644
--- a/src/main/java/org/mockito/internal/verification/checkers/AtLeastXNumberOfInvocationsInOrderChecker.java
+++ b/src/main/java/org/mockito/internal/verification/checkers/AtLeastXNumberOfInvocationsInOrderChecker.java
@@ -6,10 +6,10 @@
package org.mockito.internal.verification.checkers;
import static org.mockito.exceptions.Reporter.tooLittleActualInvocationsInOrder;
+import static org.mockito.internal.invocation.InvocationMarker.markVerifiedInOrder;
import java.util.List;
-import org.mockito.internal.invocation.InvocationMarker;
import org.mockito.internal.invocation.InvocationMatcher;
import org.mockito.internal.invocation.InvocationsFinder;
import org.mockito.internal.verification.api.InOrderContext;
@@ -19,7 +19,6 @@
public class AtLeastXNumberOfInvocationsInOrderChecker {
private final InvocationsFinder finder = new InvocationsFinder();
- private final InvocationMarker invocationMarker = new InvocationMarker();
private final InOrderContext orderingContext;
public AtLeastXNumberOfInvocationsInOrderChecker(InOrderContext orderingContext) {
@@ -36,6 +35,6 @@ public void check(List<Invocation> invocations, InvocationMatcher wanted, int wa
throw tooLittleActualInvocationsInOrder(new AtLeastDiscrepancy(wantedCount, actualCount), wanted, lastLocation);
}
- invocationMarker.markVerifiedInOrder(chunk, wanted, orderingContext);
+ markVerifiedInOrder(chunk, wanted, orderingContext);
}
}
\ No newline at end of file
diff --git a/src/main/java/org/mockito/internal/verification/checkers/NonGreedyNumberOfInvocationsInOrderChecker.java b/src/main/java/org/mockito/internal/verification/checkers/NonGreedyNumberOfInvocationsInOrderChecker.java
index a6c205b06a..6f40481ee8 100644
--- a/src/main/java/org/mockito/internal/verification/checkers/NonGreedyNumberOfInvocationsInOrderChecker.java
+++ b/src/main/java/org/mockito/internal/verification/checkers/NonGreedyNumberOfInvocationsInOrderChecker.java
@@ -5,8 +5,11 @@
package org.mockito.internal.verification.checkers;
-import org.mockito.exceptions.Reporter;
-import org.mockito.internal.invocation.InvocationMarker;
+import static org.mockito.exceptions.Reporter.tooLittleActualInvocationsInOrder;
+import static org.mockito.internal.invocation.InvocationMarker.markVerified;
+
+import java.util.List;
+
import org.mockito.internal.invocation.InvocationMatcher;
import org.mockito.internal.invocation.InvocationsFinder;
import org.mockito.internal.reporting.Discrepancy;
@@ -14,22 +17,16 @@
import org.mockito.invocation.Invocation;
import org.mockito.invocation.Location;
-import static org.mockito.exceptions.Reporter.tooLittleActualInvocationsInOrder;
-
-import java.util.List;
-
public class NonGreedyNumberOfInvocationsInOrderChecker {
private final InvocationsFinder finder;
- private final InvocationMarker marker;
public NonGreedyNumberOfInvocationsInOrderChecker() {
- this(new InvocationsFinder(), new InvocationMarker());
+ this(new InvocationsFinder());
}
- NonGreedyNumberOfInvocationsInOrderChecker(InvocationsFinder finder, InvocationMarker marker ) {
+ NonGreedyNumberOfInvocationsInOrderChecker(InvocationsFinder finder ) {
this.finder = finder;
- this.marker = marker;
}
public void check(List<Invocation> invocations, InvocationMatcher wanted, int wantedCount, InOrderContext context) {
@@ -40,7 +37,7 @@ public void check(List<Invocation> invocations, InvocationMatcher wanted, int wa
if( next == null ){
throw tooLittleActualInvocationsInOrder(new Discrepancy(wantedCount, actualCount), wanted, lastLocation );
}
- marker.markVerified( next, wanted );
+ markVerified( next, wanted );
context.markVerified( next );
lastLocation = next.getLocation();
actualCount++;
diff --git a/src/main/java/org/mockito/internal/verification/checkers/NumberOfInvocationsChecker.java b/src/main/java/org/mockito/internal/verification/checkers/NumberOfInvocationsChecker.java
index 7b277e880b..15c7594a47 100644
--- a/src/main/java/org/mockito/internal/verification/checkers/NumberOfInvocationsChecker.java
+++ b/src/main/java/org/mockito/internal/verification/checkers/NumberOfInvocationsChecker.java
@@ -8,10 +8,10 @@
import static org.mockito.exceptions.Reporter.neverWantedButInvoked;
import static org.mockito.exceptions.Reporter.tooLittleActualInvocations;
import static org.mockito.exceptions.Reporter.tooManyActualInvocations;
+import static org.mockito.internal.invocation.InvocationMarker.markVerified;
import java.util.List;
-import org.mockito.internal.invocation.InvocationMarker;
import org.mockito.internal.invocation.InvocationMatcher;
import org.mockito.internal.invocation.InvocationsFinder;
import org.mockito.internal.reporting.Discrepancy;
@@ -21,8 +21,6 @@
public class NumberOfInvocationsChecker {
private final InvocationsFinder finder=new InvocationsFinder();
- private final InvocationMarker invocationMarker = new InvocationMarker();
-
public void check(List<Invocation> invocations, InvocationMatcher wanted, int wantedCount) {
List<Invocation> actualInvocations = finder.findInvocations(invocations, wanted);
@@ -41,6 +39,6 @@ public void check(List<Invocation> invocations, InvocationMatcher wanted, int wa
throw tooManyActualInvocations(wantedCount, actualCount, wanted, firstUndesired);
}
- invocationMarker.markVerified(actualInvocations, wanted);
+ markVerified(actualInvocations, wanted);
}
}
\ No newline at end of file
diff --git a/src/main/java/org/mockito/internal/verification/checkers/NumberOfInvocationsInOrderChecker.java b/src/main/java/org/mockito/internal/verification/checkers/NumberOfInvocationsInOrderChecker.java
index 5063955968..c9a769546d 100644
--- a/src/main/java/org/mockito/internal/verification/checkers/NumberOfInvocationsInOrderChecker.java
+++ b/src/main/java/org/mockito/internal/verification/checkers/NumberOfInvocationsInOrderChecker.java
@@ -7,10 +7,10 @@
import static org.mockito.exceptions.Reporter.tooLittleActualInvocationsInOrder;
import static org.mockito.exceptions.Reporter.tooManyActualInvocationsInOrder;
+import static org.mockito.internal.invocation.InvocationMarker.markVerifiedInOrder;
import java.util.List;
-import org.mockito.internal.invocation.InvocationMarker;
import org.mockito.internal.invocation.InvocationMatcher;
import org.mockito.internal.invocation.InvocationsFinder;
import org.mockito.internal.reporting.Discrepancy;
@@ -19,10 +19,8 @@
import org.mockito.invocation.Location;
public class NumberOfInvocationsInOrderChecker {
-
private final InvocationsFinder finder;
- private final InvocationMarker invocationMarker = new InvocationMarker();
public NumberOfInvocationsInOrderChecker() {
this(new InvocationsFinder());
@@ -30,7 +28,6 @@ public NumberOfInvocationsInOrderChecker() {
NumberOfInvocationsInOrderChecker(InvocationsFinder finder) {
this.finder = finder;
-
}
public void check(List<Invocation> invocations, InvocationMatcher wanted, int wantedCount, InOrderContext context) {
@@ -47,6 +44,6 @@ public void check(List<Invocation> invocations, InvocationMatcher wanted, int wa
throw tooManyActualInvocationsInOrder(wantedCount, actualCount, wanted, firstUndesired);
}
- invocationMarker.markVerifiedInOrder(chunk, wanted, context);
+ markVerifiedInOrder(chunk, wanted, context);
}
}
\ No newline at end of file
| diff --git a/src/test/java/org/mockito/internal/invocation/InvocationMarkerTest.java b/src/test/java/org/mockito/internal/invocation/InvocationMarkerTest.java
index d85320c485..777e76b517 100644
--- a/src/test/java/org/mockito/internal/invocation/InvocationMarkerTest.java
+++ b/src/test/java/org/mockito/internal/invocation/InvocationMarkerTest.java
@@ -17,13 +17,12 @@ public class InvocationMarkerTest extends TestBase {
@Test
public void shouldMarkInvocationAsVerified() {
//given
- InvocationMarker marker = new InvocationMarker();
Invocation i = new InvocationBuilder().toInvocation();
InvocationMatcher im = new InvocationBuilder().toInvocationMatcher();
assertFalse(i.isVerified());
//when
- marker.markVerified(Arrays.asList(i), im);
+ InvocationMarker.markVerified(Arrays.asList(i), im);
//then
assertTrue(i.isVerified());
@@ -32,7 +31,6 @@ public void shouldMarkInvocationAsVerified() {
@Test
public void shouldCaptureArguments() {
//given
- InvocationMarker marker = new InvocationMarker();
Invocation i = new InvocationBuilder().toInvocation();
final ObjectBox box = new ObjectBox();
CapturesArgumentsFromInvocation c = new CapturesArgumentsFromInvocation() {
@@ -41,7 +39,7 @@ public void captureArgumentsFrom(Invocation i) {
}};
//when
- marker.markVerified(Arrays.asList(i), c);
+ InvocationMarker.markVerified(Arrays.asList(i), c);
//then
assertEquals(i, box.getObject());
@@ -51,14 +49,14 @@ public void captureArgumentsFrom(Invocation i) {
public void shouldMarkInvocationsAsVerifiedInOrder() {
//given
InOrderContextImpl context = new InOrderContextImpl();
- InvocationMarker marker = new InvocationMarker();
+
Invocation i = new InvocationBuilder().toInvocation();
InvocationMatcher im = new InvocationBuilder().toInvocationMatcher();
assertFalse(context.isVerified(i));
assertFalse(i.isVerified());
//when
- marker.markVerifiedInOrder(Arrays.asList(i), im, context);
+ InvocationMarker.markVerifiedInOrder(Arrays.asList(i), im, context);
//then
assertTrue(context.isVerified(i));
diff --git a/src/test/java/org/mockito/internal/verification/checkers/AtLeastXNumberOfInvocationsCheckerTest.java b/src/test/java/org/mockito/internal/verification/checkers/AtLeastXNumberOfInvocationsCheckerTest.java
index 9dfb7ca1c7..9e318a4611 100644
--- a/src/test/java/org/mockito/internal/verification/checkers/AtLeastXNumberOfInvocationsCheckerTest.java
+++ b/src/test/java/org/mockito/internal/verification/checkers/AtLeastXNumberOfInvocationsCheckerTest.java
@@ -5,22 +5,20 @@
package org.mockito.internal.verification.checkers;
import static java.util.Arrays.asList;
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.eq;
+import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
-import org.mockito.Mockito;
-import org.mockito.internal.invocation.*;
+import org.mockito.internal.invocation.InvocationBuilder;
+import org.mockito.internal.invocation.InvocationMatcher;
import org.mockito.invocation.Invocation;
-import org.mockitoutil.TestBase;
-public class AtLeastXNumberOfInvocationsCheckerTest extends TestBase {
+public class AtLeastXNumberOfInvocationsCheckerTest {
@Test
public void shouldMarkActualInvocationsAsVerified() {
//given
AtLeastXNumberOfInvocationsChecker c = new AtLeastXNumberOfInvocationsChecker();
- c.invocationMarker = Mockito.mock(InvocationMarker.class);
+
Invocation invocation = new InvocationBuilder().simpleMethod().toInvocation();
Invocation invocationTwo = new InvocationBuilder().differentMethod().toInvocation();
@@ -28,6 +26,6 @@ public void shouldMarkActualInvocationsAsVerified() {
c.check(asList(invocation, invocationTwo), new InvocationMatcher(invocation), 1);
//then
- Mockito.verify(c.invocationMarker).markVerified(eq(asList(invocation)), any(CapturesArgumentsFromInvocation.class));
+ assertThat(invocation.isVerified()).isTrue();
}
}
| train | train | 2016-06-14T00:01:34 | "2016-06-11T13:23:18Z" | ChristianSchwarz | train |
mockito/mockito/438_444 | mockito/mockito | mockito/mockito/438 | mockito/mockito/444 | [
"timestamp(timedelta=0.0, similarity=0.9620624077314136)",
"keyword_pr_to_issue"
] | d6480148b28defa299b25230abe7f463f850350a | e75b07853f855e2ae990a87a2cd50b971eed7cff | [
"@smoyer64 I think that is a reasonable addition. Do you maybe have a sample JUnit test case that I can add to our test suite as regression test?\n",
"@TimvdLippe,\n\nWill this change be going into Mockito 1.x or 2.x (or both)?\n",
"@sbrannen Mockito 2.0. We might be able to port back to Mockito 1.x but I would prefer not to. Is there an explicit requirement for this change to be included in 1.x?\n",
"Regarding a regression test, this should do the job!\n\n``` java\nimport static org.junit.Assert.assertTrue;\n\nimport java.lang.reflect.Field;\nimport java.lang.reflect.Method;\n\nimport org.junit.Test;\nimport org.mockito.Mock;\n\n/**\n * It's actually sufficient if this class compiles. The test methods\n * are therefore a bit superfluous.\n *\n * @author Sam Brannen\n */\npublic class MockAnnotationDeclarationTests {\n\n @Mock\n String foo;\n\n void bar(@Mock String baz) {\n }\n\n @Test\n public void mockAnnotationCanBeDeclaredOnField() throws Exception {\n Field field = getClass().getDeclaredField(\"foo\");\n assertTrue(field.isAnnotationPresent(Mock.class));\n }\n\n @Test\n public void mockAnnotationCanBeDeclaredOnParameter() throws Exception {\n Method method = getClass().getDeclaredMethod(\"bar\", String.class);\n assertTrue(method.getParameters()[0].isAnnotationPresent(Mock.class));\n }\n\n}\n```\n\nSo feel free to use that.\n\nCheers,\n\nSam\n",
"@TimvdLippe,\n\nI don't suppose there is an explicit _requirement_ per se to have this support in 1.x; however, I feel it could well benefit 1.x users who also wish to use JUnit 5. Furthermore, I cannot foresee any possible negative side effects for 1.x users: it's 100% backwards compatible.\n",
"I do not think we really have an infrastructure to still publish Mockito 1 artifacts. We did however not change much in 2 and 99% of all Mockito code should run as expected after updating. Mainly, we removed deprecated code that people had years to upgrade.\n\nI think adding this should be okay even though there is no scenario where Mockito itself would process the annotation. Would adding an annotation to the JUnit plugin not be another altivertive? I wonder if that was a cleaner solution.\n",
"> Would adding an annotation to the JUnit plugin not be another altivertive? I wonder if that was a cleaner solution.\n\nIntroducing a new annotation in Mockito's official JUnit 5 support is of course technically possible -- that's what our proof-of-concept `MockitoExtension` does today (i.e., we created an `@InjectMock` annotation).\n\nBut... I don't think I would call that a _cleaner solution_. IMHO, a single annotation from Mockito would be the cleanest solution since it would result in the **element of least surprise** for users of Mockito.\n\nFWIW, we have already hashed out the [exact same discussion for the Spring Framework](https://jira.spring.io/browse/SPR-14057) with regard to Spring's `@Autowired` annotation. Previously, it was not allowed to be declared on a constructor or method parameter, but we changed this for Spring 4.3.\n",
"Ok, considering that JUnit and Mockito is such a common combination, let's just make it as easy as possible.\n",
"Sounds good! 👍 \n",
"Wow ... a lot of work got done while I was out celebrating Father's Day. From a user's perspective, this all looks perfect. How often do you get everything you ask for? I guess I have one final question which, since this issue is closed, is more academic - where should an official, production ready MockitoExtension for JUnit 5 be hosted? MockitoJunit is obviously part of the Mockito project and the MokitoExtension will always rely on both Mockito and JUnit 5.\n\nMaintaining the status quo would be fine, but it might also make sense to create a junit5-extensions project for \"common combinations\" (using the wording above), where a combination of project maintainers could collaborate on code that is essentially the intersection of their projects? External Extensions and TestEngines are going to be documented in the JUnit 5 wiki per issue https://github.com/junit-team/junit5/issues/297 and, given the collaboration demonstrated by this thread, maybe the whole question is moot.\n\nIn any case, thanks for all the hard work that's gone into both projects!\n",
"@smoyer64 You got lucky we are working hard on releasing Mockito 2.0 :smile: \n\nI am not sure what the stance is of the JUnit team regarding such extensions. Could you open an issue on JUnit5 to discuss where such extensions should be placed?\n",
"@TimvdLippe \n\nThe question has been posed to the JUnit 5 team in issue https://github.com/junit-team/junit5/issues/321. @sbrannen is a member of that team, so I'm guessing he's already seen the question ;). And I'm just one of those pesky users (trying to help identify use cases and stress-test the new code)!\n",
"Thanks a lot. Looking forward to their response.\n"
] | [
"Awesome! 👍 \n"
] | "2016-06-19T12:08:08Z" | [
"enhancement"
] | Add ElementType.PARAMETER to @Mock | Parameterized tests are becoming more common - JUnit 5 explicitly allows parameters and the sample [MockitoExtension](https://github.com/junit-team/junit5-samples/tree/master/junit5-mockito-extension/src/main/java/com/example/mockito) currently includes an @InjectMock to trigger the creation of a mock parameter. It would be so much cleaner to use @Mock in both places.
This shouldn't be an issue for most legacy test systems since they don't allow test parameters (by default).
| [
"src/main/java/org/mockito/Mock.java"
] | [
"src/main/java/org/mockito/Mock.java"
] | [] | diff --git a/src/main/java/org/mockito/Mock.java b/src/main/java/org/mockito/Mock.java
index 91cb0538c8..2988cb2cba 100644
--- a/src/main/java/org/mockito/Mock.java
+++ b/src/main/java/org/mockito/Mock.java
@@ -9,6 +9,7 @@
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.FIELD;
+import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
@@ -58,7 +59,7 @@
* @see MockitoAnnotations#initMocks(Object)
* @see org.mockito.runners.MockitoJUnitRunner
*/
-@Target(FIELD)
+@Target({FIELD, PARAMETER})
@Retention(RUNTIME)
@Documented
public @interface Mock {
| null | train | train | 2016-06-19T13:43:27 | "2016-06-18T17:10:29Z" | smoyer64 | train |
mockito/mockito/453_454 | mockito/mockito | mockito/mockito/453 | mockito/mockito/454 | [
"keyword_pr_to_issue"
] | ce957844a9adc8403434ccf893b9d68d047573e9 | 9af742d476dbfc746e2cb09698af3524c96b49ec | [
"I can't imagine a scenario where the parameterized type cause problems and why it aids debuging if no type parameter is used.\n\n@all Do we have examples that illustrate the described problem? If not the JavaDoc should be removed!\n",
"#454 is one way we could wrap this up. Sorry for not noticing it sooner!\n",
"If we receive such a report, we should catch such an exception and log an appropriate error why this is happening. For now I can't see this breaking, but I am happy to be proven wrong.\n"
] | [] | "2016-06-21T08:23:44Z" | [] | Either revert recent Functional Interfaces change or change JavaDoc | I've been reading the Javadoc regarding `ArgumentMatcher` and I noticed a couple of things. Relating back to the changes of #338
- The example of how to override it is still based around `Object` rather than `T`
- Someone has very deliberately decided not to make it use `T` in the past and now we've changed that.
> The argument is not using the generic type in order to force explicit casting in the implementation. This way it is easier to debug when incompatible arguments are passed to the matchers. You have to trust us on this one. If we used parametrized type then ClassCastException would be thrown in certain scenarios.
My view at the time was that changing it to `T` would remove the class casting and that this would be a good thing. It was kind of necessary to have it as `T` so that the lambda expressions in Java 8 could infer the right types.
The rationale about a class cast exception giving weird results kind of makes sense, but does that really really happen? It seems it's either solve one problem or the other.
What do folks think? I'll happily amend the code either way.
| [
"src/main/java/org/mockito/ArgumentMatcher.java"
] | [
"src/main/java/org/mockito/ArgumentMatcher.java"
] | [] | diff --git a/src/main/java/org/mockito/ArgumentMatcher.java b/src/main/java/org/mockito/ArgumentMatcher.java
index 3b2e3d19c4..8b9abd0ce4 100644
--- a/src/main/java/org/mockito/ArgumentMatcher.java
+++ b/src/main/java/org/mockito/ArgumentMatcher.java
@@ -35,6 +35,8 @@
* Useful if you already have a hamcrest matcher. Reuse and win!
* Note that {@link org.mockito.hamcrest.MockitoHamcrest#argThat(org.hamcrest.Matcher)} demonstrates <b>NullPointerException</b> auto-unboxing caveat.
* </li>
+ * <li>Java 8 only - use a lambda in place of an {@link ArgumentMatcher} since {@link ArgumentMatcher}
+ * is effectively a functional interface. A lambda can be used with the {@link Mockito#argThat} method.</li>
* </ul>
*
* <p>
@@ -44,8 +46,8 @@
*
* <pre class="code"><code class="java">
* class ListOfTwoElements implements ArgumentMatcher<List> {
- * public boolean matches(Object list) {
- * return ((List) list).size() == 2;
+ * public boolean matches(List list) {
+ * return list.size() == 2;
* }
* public String toString() {
* //printed in verification errors
@@ -93,6 +95,7 @@
* b) Use <code>org.mockito.hamcrest.MockitoHamcrest.argThat()</code> instead of <code>Mockito.argThat()</code>.
* Ensure that there is <a href="http://hamcrest.org/JavaHamcrest/">hamcrest</a> dependency on classpath
* (Mockito does not depend on hamcrest any more).
+ *
* </li>
* </ul>
* What option is right for you? If you don't mind compile dependency to hamcrest
@@ -111,22 +114,6 @@ public interface ArgumentMatcher<T> {
* The method should <b>never</b> assert if the argument doesn't match. It
* should only return false.
* <p>
- * The argument is not using the generic type in order to force explicit casting in the implementation.
- * This way it is easier to debug when incompatible arguments are passed to the matchers.
- * You have to trust us on this one. If we used parametrized type then <code>ClassCastException</code>
- * would be thrown in certain scenarios.
- * For example:
- *
- * <pre class="code"><code class="java">
- * //test, method accepts Collection argument and ArgumentMatcher<List> is used
- * when(mock.useCollection(someListMatcher())).thenDoNothing();
- *
- * //production code, yields confusing ClassCastException
- * //although Set extends Collection but is not compatible with ArgumentMatcher<List>
- * mock.useCollection(new HashSet());
- * </pre>
- *
- * <p>
* See the example in the top level javadoc for {@link ArgumentMatcher}
*
* @param argument
| null | val | train | 2016-06-20T00:57:18 | "2016-06-20T19:33:24Z" | ashleyfrieze | train |
mockito/mockito/226_481 | mockito/mockito | mockito/mockito/226 | mockito/mockito/481 | [
"timestamp(timedelta=0.0, similarity=0.932913327674623)",
"keyword_pr_to_issue"
] | 1eddf98e096c8d55a4f5a0bc08947003e9448c81 | b0393eafeeb81b6c75e40a82b81672543777ca9a | [
"Great idea.\n"
] | [] | "2016-07-06T11:02:06Z" | [
"docs",
"continuous integration"
] | Exclude internal package from javadoc | Internal package don't need to be included in the javadoc generation, just like the jdk doesn't have `com.sun` package
In the javadoc that may be done via a doclet since `exclude '**/internal/**'` raise javadoc errors
``` groovy
doclet = "qualified.name.of.DocletExclude"
docletpath = [rootProject.file('./gradle/doclet-exclude.jar')]
```
| [
"buildSrc/build.gradle",
"gradle/javadoc.gradle",
"gradle/wrapper/gradle-wrapper.properties"
] | [
"buildSrc/build.gradle",
"buildSrc/src/main/java/org/mockito/javadoc/JavadocExclude.java",
"gradle/javadoc.gradle",
"gradle/wrapper/gradle-wrapper.properties"
] | [] | diff --git a/buildSrc/build.gradle b/buildSrc/build.gradle
index 28c2cd953a..6720ba5a90 100644
--- a/buildSrc/build.gradle
+++ b/buildSrc/build.gradle
@@ -8,6 +8,7 @@ dependencies {
//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"
+ compile files("${System.properties['java.home']}/../lib/tools.jar")
testCompile("org.spockframework:spock-core:0.7-groovy-2.0") {
exclude module: "groovy-all"
}
diff --git a/buildSrc/src/main/java/org/mockito/javadoc/JavadocExclude.java b/buildSrc/src/main/java/org/mockito/javadoc/JavadocExclude.java
new file mode 100644
index 0000000000..3464f0b426
--- /dev/null
+++ b/buildSrc/src/main/java/org/mockito/javadoc/JavadocExclude.java
@@ -0,0 +1,70 @@
+package org.mockito.javadoc;
+
+import com.sun.javadoc.*;
+import com.sun.tools.doclets.formats.html.HtmlDoclet;
+
+import java.lang.reflect.InvocationHandler;
+import java.lang.reflect.Method;
+import java.lang.reflect.Proxy;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Doclet built to exclude mockito internal packages from the outputted Javadoc.
+ * All methods except the start method are copied from {@link com.sun.tools.doclets.standard.Standard}.
+ * Inspired by https://gist.github.com/benjchristensen/1410681
+ */
+public class JavadocExclude {
+
+ public static int optionLength(String var0) {
+ return HtmlDoclet.optionLength(var0);
+ }
+
+ public static boolean start(RootDoc root) {
+ Class clz = root.getClass();
+ return HtmlDoclet.start((RootDoc) Proxy.newProxyInstance(clz.getClassLoader(), clz.getInterfaces(), new ExcludeHandler(root)));
+ }
+
+ public static boolean validOptions(String[][] var0, DocErrorReporter var1) {
+ return HtmlDoclet.validOptions(var0, var1);
+ }
+
+ public static LanguageVersion languageVersion() {
+ return HtmlDoclet.languageVersion();
+ }
+
+ /**
+ * Proxy which filters the {@link RootDoc#classes()} method to filter {@link ClassDoc} based on their package name.
+ */
+ private static class ExcludeHandler implements InvocationHandler {
+ private final RootDoc root;
+
+ private ExcludeHandler(RootDoc root) {
+ this.root = root;
+ }
+
+ @Override
+ public Object invoke(Object o, Method method, Object[] args) throws Throwable {
+ Object result = method.invoke(root, args);
+ if (result instanceof Object[]) {
+ List<ClassDoc> filteredDocs = new ArrayList<ClassDoc>();
+ Object[] array = (Object[]) result;
+ for (Object entry : array) {
+ if (entry instanceof ClassDoc) {
+ ClassDoc doc = (ClassDoc) entry;
+ if (!doc.containingPackage().name().startsWith("org.mockito.internal")) {
+ filteredDocs.add(doc);
+ }
+ }
+ }
+ // If no ClassDoc were found in the original array,
+ // since PackageDoc area also included in the classes array.
+ if (filteredDocs.size() > 0) {
+ ClassDoc[] docArray = new ClassDoc[filteredDocs.size()];
+ return filteredDocs.toArray(docArray);
+ }
+ }
+ return result;
+ }
+ }
+}
diff --git a/gradle/javadoc.gradle b/gradle/javadoc.gradle
index 4d5daa5d43..51f4cd4e1d 100644
--- a/gradle/javadoc.gradle
+++ b/gradle/javadoc.gradle
@@ -14,6 +14,8 @@ task mockitoJavadoc(type: Javadoc) {
title = "Mockito ${project.version} API"
def javadocJdk6Hack = "jdk6-project-version-insert.min.js"
+ options.doclet "org.mockito.javadoc.JavadocExclude"
+ options.docletpath = [rootProject.file('./buildSrc/build/classes/main/')]
options.docTitle = """<h1><a href="org/mockito/Mockito.html">Click to see examples</a>. Mockito ${project.version} API.</h1>"""
options.windowTitle = "Mockito ${project.version} API"
options.group("Main package", ["org.mockito"])
diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties
index 80cbe6ead4..0b5a32f1e1 100644
--- a/gradle/wrapper/gradle-wrapper.properties
+++ b/gradle/wrapper/gradle-wrapper.properties
@@ -1,6 +1,6 @@
-#Sun Mar 09 16:13:07 CET 2016
+#Wed Jul 06 11:31:59 CEST 2016
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
-distributionUrl=https\://services.gradle.org/distributions/gradle-2.11-bin.zip
+distributionUrl=https\://services.gradle.org/distributions/gradle-2.11-all.zip
| null | val | train | 2016-07-05T17:03:31 | "2015-06-06T21:23:36Z" | bric3 | train |
mockito/mockito/123_483 | mockito/mockito | mockito/mockito/123 | mockito/mockito/483 | [
"keyword_issue_to_pr",
"keyword_pr_to_issue"
] | d01911eb9040d21ba6763dfb90c5210bb480e1b9 | 80ab0db765138a57b105c7a64676ebc38cb94f35 | [
"Is it still planned for 2.0 to give users an option to use an alternative to cglib (like Byte Buddy)?\n",
"This kind of feature can be added any time (e.g. it's not a backwards-incompatible change). It's just someone needs to implement it :) \n\nSo short answer is 'no', it's not planned for 2.0 (but I would love to have this feature soon)\n",
"If possible I would really like to replace CGLIB by bytebuddy.\n\nI wanted to craft an external MockMaker but I'm way too much overwhelmed at the moment. The code exists in my clone though.\n",
"@bric3, you mean that you're keen on changing default proxy mechanism in 2.0? I'm fine with this :) I do want to publish 2.0 this year though and I won't be very active it this part of the code. So, if you make it, it can be included :)\n",
"@szczepiq You mean by the end of 2014 ?\n\nWhat I hoped was to build a mockmaker that could be tested on the 1.x. But the code may replace CGLIB now if necessary. Beta have to be tested by other people though, I especially think about uncommon environment like OSGI, etc...\n",
"1>You mean by the end of 2014 ?\n\nhaha, yeah ;)\n\n> What I hoped was to build a mockmaker that could be tested on the 1.x.\n\nLike an opt-in feature for 1.x?\n\nI definitely think that given we have the bytebuddy impl of MockMaker, we\nshould make it conveniently pluggable instead of just replacing cglib\ncompletely. You mentioned earlier that you had the ByteBuddy MockMaker\nworking with Mockito test suite?\n\nCheers!\n\nOn Mon, Nov 24, 2014 at 4:18 PM, Brice Dutheil notifications@github.com\nwrote:\n\n> You mean by the end of 2014 ?\n> \n> What I hoped was to build a mockmaker that could be tested on the 1.x. But\n> the code may replace CGLIB now if necessary. Beta have to be tested by\n> other people though, I especially think about uncommon environment like\n> OSGI, etc...\n> \n> ## \n> \n> Reply to this email directly or view it on GitHub\n> https://github.com/mockito/mockito/issues/123#issuecomment-64208043.\n\n## \n\nSzczepan Faber\nCore dev@gradle; Founder@mockito\n",
"> > What I hoped was to build a mockmaker that could be tested on the 1.x.\n> \n> Like an opt-in feature for 1.x?\n\nYes. But, meanwhile replacing CGLIB in mockito 2.0.\n\n> You mentioned earlier that you had the ByteBuddy MockMaker working with Mockito test suite?\n\nYes it does. I just would like to ensure it works with uncommon environment like OSGI.\n",
"Do you think it is worthwhile to keep support for cglib once we have\nbytebuddy?\n\nDo you think we should shade bytebuddy? What dependencies bytebuddy brings?\n\nOn Mon, Nov 24, 2014 at 6:26 PM, Brice Dutheil notifications@github.com\nwrote:\n\n> What I hoped was to build a mockmaker that could be tested on the 1.x.\n> Like an opt-in feature for 1.x?\n> \n> Yes. But, meanwhile replacing CGLIB in mockito 2.0.\n> \n> You mentioned earlier that you had the ByteBuddy MockMaker working with\n> Mockito test suite?\n> \n> Yes it does. I just would like to ensure it works with uncommon\n> environment like OSGI.\n> \n> ## \n> \n> Reply to this email directly or view it on GitHub\n> https://github.com/mockito/mockito/issues/123#issuecomment-64229927.\n\n## \n\nSzczepan Faber\nCore dev@gradle; Founder@mockito\n",
"No I don't think it is necessary, however we can make a CGLIB mock maker, for people that may depend on it.\n",
"I am curious: Do you guys have a time-line for the 2.0 release? I am more than happy to support any code-generation releated issues. However, my vacation is approaching so I will be gone for a couple of weeks starting mid-August.\n\nIn particular, I wonder you guys wanted to try integrating Byte Buddy 0.7 with support for generic type retention already in 2.0 which I hope to complete before my vacation. One word of warning: Generic types are awefully complex. Byte Buddy needs to parse stringified type information and resolve the full type hierarchy, i.e. bind type variables of super types / interfaces to their actual values in order to appropriately resolve a type variable's value while dealing with the possibility of raw types and potentially illegally formatted generic types (the JVM does not verify generic type infromation which simply exists as meta data). There is a chance for corner case errors even though I isolated the functionality pretty much to fall back to type erasure if any illegal type information is disovered. At the same time, mocks would behave better when a generic type is read by a class processing a mock.\n",
"It must happen in 2015. I hope we are ready in the next few months. In\ntheory, there's not much left work :)\n\nCheers!\n\nOn Fri, Jul 10, 2015 at 5:31 AM, Rafael Winterhalter <\nnotifications@github.com> wrote:\n\n> I am curious: Do you guys have a time-line for the 2.0 release? I am more\n> than happy to support any code-generation releated issues. However, my\n> vacation is approaching so I will be gone for a couple of weeks starting\n> mid-August.\n> \n> —\n> Reply to this email directly or view it on GitHub\n> https://github.com/mockito/mockito/issues/123#issuecomment-120399539.\n\n## \n\nSzczepan Faber\nFounder mockito.org; Core dev gradle.org\ntweets as @szczepiq; blogs at blog.mockito.org\n",
"I think mockito 2.0 is nearly in shape to be released, most work should go in polishing remaining bits of the public API. IMHO current byte buddy version is fine, and already provide subtitle but needed enhancements.\n\nMore specifically on generics I believe current support is OK, after all mockito is a TDD tool for a rapid feedback loop, both on the dev workstation and the ci bots. I believe current generics support in the deepstubs answer is enough. About the issue you mention the support class I wrote is probably incomplete but enough, and I agree parsing this metadata is hard. Anyway at the moment if any extended support should be provided on this front it should be provided via a mockmaker plugin.\n",
"Thanks for the info. I just released Byte Buddy 0.7 but I recommend you to not yet update. Generic types are tricky and I already found a corner case in the bridge method resolution that does not work. I'll try to make it stable until the mid of August, though.\n",
"Any guess on when 2.0 will be released?\n",
"It's been silent for past couple of months, everybody busy, etc. Since\nyesterday, I'm focusing my spare time on Mockito. I will not stop until 2.0\nis out. We cannot guarantee any dates but 2.0 must be released in 2015.\n\nOn Sat, Sep 19, 2015 at 8:40 AM, David J. M. Karlsen <\nnotifications@github.com> wrote:\n\n> Any guess on when 2.0 will be released?\n> \n> —\n> Reply to this email directly or view it on GitHub\n> https://github.com/mockito/mockito/issues/123#issuecomment-141681244.\n\n## \n\nSzczepan Faber\nFounder mockito.org; Core dev gradle.org\ntweets as @szczepiq; blogs at blog.mockito.org\n",
"Any updates on when we might see a 2.0 release?\n",
"2015 is soon over ;) At some point, we need to do a cut in features. I think everybody is quite budy right now. As always, the time before Christmas are busy month for consultant work.\n",
"Soon. This year for sure. Sorry I was distracted! We will probably deliver\n2.0 with what we have, no new fancy features ;)\nOn Nov 10, 2015 4:52 AM, \"Rafael Winterhalter\" notifications@github.com\nwrote:\n\n> 2015 is soon over ;) At some point, we need to do a cut in features. I\n> think everybody is quite budy right now. As always, the time before\n> Christmas are busy month for consultant work.\n> \n> —\n> Reply to this email directly or view it on GitHub\n> https://github.com/mockito/mockito/issues/123#issuecomment-155412454.\n",
"Can this task https://github.com/mockito/mockito/issues/300 be included in 2.0 release?\n",
"Feel free to add #374 to the todo list\n",
"2.0 is coming so slow.\n",
"It's way too slow. I'm on it. Thank you guys for pushing.\n",
"@szczepiq How can we/the community support the mockito core team ?\n",
"> @szczepiq https://github.com/szczepiq How can we/the community support\n> the mockito core team ?\n> \n> You already are. You guys are great. Thank you for patience and pushing us\n> to deliver.\n\nThe lagging of beta is my fault. I've started the beta cycle and I should\nhave completed it. I'm back in the game, though.\n\nOnce 2.x final is out we need clarify how community can drive supporting\nand maintaining Mockito.\n\nNote that Mockito is continuously delivered so you can open PR to change\nthe version to \"2.1.0\", and that's it :)\n\nCheers!\n\n> —\n> You are receiving this because you were mentioned.\n> Reply to this email directly or view it on GitHub\n> https://github.com/mockito/mockito/issues/123#issuecomment-206757516\n",
"@szczepiq I left a pull request for removing deprecated code which is an 2.0 milestone issue - can you pull it/looks good?\n",
"I haven't reviewed yet. THANKS!\nOn Sun, Apr 10, 2016 at 03:12 David J. M. Karlsen notifications@github.com\nwrote:\n\n> @szczepiq https://github.com/szczepiq I left a pull request for\n> removing deprecated code which is an 2.0 milestone issue - can you pull\n> it/looks good?\n> \n> —\n> You are receiving this because you were mentioned.\n> Reply to this email directly or view it on GitHub\n> https://github.com/mockito/mockito/issues/123#issuecomment-207953253\n",
"Per Mockito developers discussion:\n\nWe want to target publishing the release on July 31st with a release candidate on June 30th.\n\nThere is one issue which must be resolved for that, which is #194. Other than that I just found 1 minor TODO [in the Mockito documentation](https://github.com/mockito/mockito/blob/dff5510cb3e97dae414e58ba85825ad01b273c72/src/main/java/org/mockito/Mockito.java#L1091). The other issues can be fixed in a later minor version.\n",
"@TimvdLippe what about https://github.com/mockito/mockito/issues/300?\n",
"@skabashnyuk I think that we still want to do this, but is not a blocker for the release. We must do it when we have time, but it is okay in my opinion to release it in a later minor version. I have to be honest that I was not participating in the original discussion so I do not know the exact details. @bric3 is the man to talk to :)\n",
"@TimvdLippe @skabashnyuk Humm I think we should really focus energy on mockito 2, TestNG could come later.\n",
"> TestNG could come later.\n\n@bric3 No problem. But why this can't be done in parallel? Code is ready, looks like this is an infrastructure-deployment issue. Or you are planning to do something bigger than just deploy artifacts?\n",
"@skabashnyuk Currently we are focused on releasing Mockito 2.0. This leaves little to no time for other issues sadly. If you are able to configure the deployment, we are happy to accept your pull request! We can devote some of our time to the TestNG issue after we have released Mockito 2.0.\n",
"Some update.\n\nWe're not ready for the release but there's good momentum. Let's plan out\nwhat else needs to be done (announcement information, really documentation\naround why to upgrade and how, solid plan what's next after the release\ncandidate, etc.).\n\nI'm confident the RC will be out in August. I plan to announce everywhere\nthat we plan RB in August. If we don't meet the date there will high degree\nof shame ;) Thoughts?\n\nOn Sat, Jun 25, 2016 at 3:59 AM, Tim van der Lippe <notifications@github.com\n\n> wrote:\n> \n> @skabashnyuk https://github.com/skabashnyuk Currently we are focused on\n> releasing Mockito 2.0. This leaves little to no time for other issues\n> sadly. If you are able to configure the deployment, we are happy to accept\n> your pull request! We can devote some of our time to the TestNG issue after\n> we have released Mockito 2.0.\n> \n> —\n> You are receiving this because you were mentioned.\n> Reply to this email directly, view it on GitHub\n> https://github.com/mockito/mockito/issues/123#issuecomment-228532419,\n> or mute the thread\n> https://github.com/notifications/unsubscribe/AABgp8m2jG-9Rj7USJ1V2s6GJNHLzbdwks5qPQodgaJpZM4C_fdm\n> .\n\n## \n\nSzczepan Faber\nFounder @ mockito.org | Twitter @ szczepiq\nAuthor @ https://www.linkedin.com/today/author/6016386\n",
"I think most of the work should be focused on the upgrade guide, there's not much left for 2.0, follow up tasks can be completed in 2.1\n",
"I think we can publish the release candidate while working on the actual upgrade guide (state this in the github release for users to follow). The only two issues that are non-documentation are #384 with PR #527 of @szczepiq and #489 with PR #491 of myself. #527 has some feedback to be processed and #491 is more of a discussion regarding the runner.\n\nOnce these two are resolved, we can merge #483 and the release candidate is published :tada: \n\nFor an up-to-date status, see https://waffle.io/mockito/mockito and https://github.com/mockito/mockito/milestone/1\n",
"This is great stuff!!! Thanks a lot Tim for pushing the release forward & organizing it so well.\n\nI'm making good progress on the warnings stuff for JUnit rule and the listener - will update the PR very soon.\n",
"I'm confused why this ticket is closed. I don't see 2.0 in maven central :)\n",
"@szczepiq because this issue was referenced in #483 which I just merged\n",
"ah, GH smartness :)\n",
"As promised here’s suggested plan to get 2.0 out. Please give feedback, sing up for tasks and commit to ETA so that we get 2.0 out :)\n\nStep 1:\n- [ ] prepare RC release notes + announcement (highlights, motivation, request for feedback) - #582\n- [ ] review and update documentation for 2.0.0 - #596\n- [ ] ensure & test manual Mockito releases - #586\n- [ ] update CI / build scripts (releasing betas from branch, etc) - #594\n\nStep 2:\n- [ ] branch out / fixes to release / Travis - #594\n\nStep 3:\n- [ ] pull the trigger for RC!!!!!, close darn #123 !!!!!!\n",
"![image](https://cloud.githubusercontent.com/assets/5948271/18092170/97fac1ca-6ecb-11e6-83e0-fd2953833359.png)\n",
"I think we have updated all relevant documentation. @bric3 once you branch out to `release/2.x` we can publish the release candidate :tada: \n",
"I went ahead and published the release candidate. You can download `2.1.0-RC.1` at https://bintray.com/szczepiq/maven/mockito/2.1.0-RC.1#\n",
"By the way I would prefer to have mockito account on bintray \n",
"Yes agreed. Let's extract a separate issue for that.\n",
"Mockito 2.1.0 has been released, upgrade today :tada: \n"
] | [] | "2016-07-07T13:52:49Z" | [
"epic"
] | Release Mockito 2.0 | Incompatible changes:
- [x] stop producing mockito-all #153
- [x] stop depending on hamcrest internally #154
- [x] use newer hamcrest #232
- [x] make the anyXxx and any(Xxx) matchers intuitive #134, #194
- ~~fix the site links~~
- [x] push cglib mockmaker to a separate jar #248
- [x] stop using ant for producing OSGi bundles. No more ant in the build #249
- [x] remove jars from source distribution #250
- ~~perhaps introduce is() matcher~~ #246
- ~~richer and smarter stubbing~~ #303
- ~~support java8 features for capturing arguments and matchers~~
- [x] make the JUnitRule and the runner verbose
- [x] ensure release notes can be neatly generated for the RC #582
Possibly compatible (and hence, could be released pre-2.0 if needed)
- [x] drop deprecated code
- [x] unincubate API
- ~~drop serialVersionUID~~
| [
"README.md",
"buildSrc/src/main/groovy/org/mockito/release/version/VersionBumper.java",
"version.properties"
] | [
"README.md",
"buildSrc/src/main/groovy/org/mockito/release/version/VersionBumper.java",
"version.properties"
] | [
"buildSrc/src/test/groovy/org/mockito/release/version/VersionBumperTest.groovy"
] | diff --git a/README.md b/README.md
index 1ffdd450c9..d3595e27fc 100644
--- a/README.md
+++ b/README.md
@@ -17,24 +17,34 @@ See the [release notes page](https://github.com/mockito/mockito/blob/master/doc/
## Versioning
-Mockito has an automated release system, which imposed some change on how the version numbers work. While this is similar to [_semver_](http://semver.org/), there's some differences. Let's look at the following versions `1.10.19` and `2.0.5-beta` and `2.0.0` (not yet released). They follow this scheme:
+Mockito has an automated release system, which imposed some change on how the version numbers work.
+They follow this scheme:
```
-major.minor.build-tag
+major.minor.patch-tag.tagVersion
```
| number | meaning |
| ------ | ------------------------------------------------------------------------------------- |
-| major | major version, with most probably incompatible change in API and behavior |
-| minor | minor version, important enough change to bump this number |
-| build | a released build number incremented automatically when a pull request is merged |
-| tag | will probably be `-beta` or just nothing (during beta, breaking changes are expected) |
+| major | major version, backwards incompatible with the previous major version |
+| minor | minor version, backwards compatible with added features |
+| patch | patch version, small bug fixes or stylistic improvements |
+| tag | *optional* beta or RC (release candidate). See below. |
That means:
-* `2.0.0` and `2.0.5-beta` are binary incompatible with `1.10.19`.
-* `2.0.5-beta` is the fifth release beta of version `2.0.0`.
-* `2.0.5-beta` is a work in progress, api may change and may not be graduated in version `2.0.0`.
+* `2.0.0` and `2.0.0-beta.5` are binary incompatible with `1.10.19`.
+* `2.0.0-beta.5` is the fifth release beta of version `2.0.0`.
+* `2.0.0-beta.5` could be (but is not necessarily) binary incompatible with version `2.0.0`.
+* `2.0.0-RC.1` is binary compatible with release `2.0.0`.
+
+### Tags
+There are two different tags: beta or RC. Beta indicates that the version is directly generated from the master branch of the git repository.
+Beta releases are automatically published whenever we merge a pull request or push a change to the master branch.
+
+When we deem our master status worthy of a release, we publish a release candidate. The release candidate is scheduled to be officially published
+in the official release a while later. There will be no breaking changes between a release candidate and its equivalent official release.
+The only changes will include bug fixes or small updates. No additional features will be included.
## Looking for support
diff --git a/buildSrc/src/main/groovy/org/mockito/release/version/VersionBumper.java b/buildSrc/src/main/groovy/org/mockito/release/version/VersionBumper.java
index 01ed67cac5..b6f6ba8e54 100644
--- a/buildSrc/src/main/groovy/org/mockito/release/version/VersionBumper.java
+++ b/buildSrc/src/main/groovy/org/mockito/release/version/VersionBumper.java
@@ -9,17 +9,20 @@ class VersionBumper {
* Increments 'patch' element of the version of provided version, e.g. 1.0.0 -> 1.0.1
*/
String incrementVersion(String version) {
- Pattern pattern = Pattern.compile("(\\d+)\\.(\\d+)\\.(\\d+)(-(\\w+)){0,1}");
+ Pattern pattern = Pattern.compile("(\\d+)\\.(\\d+)\\.(\\d+)(-(\\w+)\\.(\\d+))?");
Matcher matcher = pattern.matcher(version);
boolean m = matcher.matches();
if (!m) {
- throw new IllegalArgumentException("Unsupported version: '" + version + "'. Examples of supported versions: 1.0.0, 1.20.123, 1.0.10-beta");
+ throw new IllegalArgumentException("Unsupported version: '" + version + "'. Examples of supported versions: 1.0.0, 1.20.123, 1.0.10-beta.3");
}
int major = Integer.parseInt(matcher.group(1));
int minor = Integer.parseInt(matcher.group(2));
int patch = Integer.parseInt(matcher.group(3));
- String postfix = matcher.group(4) != null ? matcher.group(4) : "";
- return "" + major + "." + minor + "." + (patch + 1) + postfix;
+ if (matcher.group(4) != null) {
+ int betaVersion = Integer.parseInt(matcher.group(6));
+ return "" + major + "." + minor + "." + patch + "-" + matcher.group(5) + "." + (betaVersion + 1);
+ }
+ return "" + major + "." + minor + "." + (patch + 1);
}
}
diff --git a/version.properties b/version.properties
index 3d70180266..d87a336523 100644
--- a/version.properties
+++ b/version.properties
@@ -1,2 +1,2 @@
-version=2.0.112-beta
+version=2.0.0-beta.112
mockito.testng.version=1.0
| diff --git a/buildSrc/src/test/groovy/org/mockito/release/version/VersionBumperTest.groovy b/buildSrc/src/test/groovy/org/mockito/release/version/VersionBumperTest.groovy
index db1c3d6835..b34bcda696 100644
--- a/buildSrc/src/test/groovy/org/mockito/release/version/VersionBumperTest.groovy
+++ b/buildSrc/src/test/groovy/org/mockito/release/version/VersionBumperTest.groovy
@@ -13,8 +13,9 @@ class VersionBumperTest extends Specification {
v.incrementVersion("0.0.0") == "0.0.1"
v.incrementVersion("1.10.15") == "1.10.16"
- v.incrementVersion("1.0.0-beta") == "1.0.1-beta"
- v.incrementVersion("1.10.15-beta") == "1.10.16-beta"
+ v.incrementVersion("1.0.0-beta.3") == "1.0.0-beta.4"
+ v.incrementVersion("1.10.15-beta.5") == "1.10.15-beta.6"
+ v.incrementVersion("2.0.0-RC.1") == "2.0.0-RC.2"
}
def "increments only 3 numbered versions"() {
@@ -25,6 +26,6 @@ class VersionBumperTest extends Specification {
thrown(IllegalArgumentException)
where:
- unsupported << ["1.0", "2", "1.0.0.0", "1.0.1-beta.2"]
+ unsupported << ["1.0", "2", "1.0.0.0", "1.0.1-beta"]
}
}
| train | train | 2016-08-22T09:50:54 | "2014-11-22T21:31:43Z" | mockitoguy | train |
mockito/mockito/478_483 | mockito/mockito | mockito/mockito/478 | mockito/mockito/483 | [
"keyword_issue_to_pr"
] | d01911eb9040d21ba6763dfb90c5210bb480e1b9 | 80ab0db765138a57b105c7a64676ebc38cb94f35 | [
"I don't think so, I believe we should keep up-to-date javadoc, but maybe pointing to released versions javadocs.\n",
"Or we could tweak the layout :\n- `current` == latest released version => `http://site.mockito.org/mockito/docs/current/org/mockito/Mockito.html`\n- `release/2.0.0` => `http://site.mockito.org/mockito/docs/2.0.0/org/mockito/Mockito.html`\n- `beta/3.0.0.beta.xxxx` => `http://site.mockito.org/mockito/docs/beta/3.0.0.beta.xxxx/org/mockito/Mockito.html`\n\nWe could have some way with javascript injection to have some menu that help switch to other versions.\n\nAnyway I think we could safely purge beta javadoc publication once 2.0.0 release https://github.com/mockito/mockito/tree/gh-pages/docs\n",
"This issue description is absolutely horrible when I read it back now. It was mainly concerning the version issues, which should be fixed in #483. The other issue is indeed the documentation, but this is mainly an issue for the website, no?\n\nAnyways, it would be to merge #483 sooner rather than later as Mockito 2.0 has been lingering for a while now. The longer we wait, the less incentivized will people be.\n",
"This issue has been resolved with the new version scheme and possibility to manually release a version\n"
] | [] | "2016-07-07T13:52:49Z" | [
"docs",
"continuous integration"
] | Improve release generator | Currently releases are generated automatically and documentation pushed to the website. However, when we are publishing a major release, this should be changed.
Probably the best solution is to disable the automatic generation for now and invoke this manually. This does require some changes to the current Gradle release process.
Also, in #79 the changelog was improved. We should take a look at improving this as well.
TLDR: Take a good look at the Gradle release process and purge/improve tasks.
| [
"README.md",
"buildSrc/src/main/groovy/org/mockito/release/version/VersionBumper.java",
"version.properties"
] | [
"README.md",
"buildSrc/src/main/groovy/org/mockito/release/version/VersionBumper.java",
"version.properties"
] | [
"buildSrc/src/test/groovy/org/mockito/release/version/VersionBumperTest.groovy"
] | diff --git a/README.md b/README.md
index 1ffdd450c9..d3595e27fc 100644
--- a/README.md
+++ b/README.md
@@ -17,24 +17,34 @@ See the [release notes page](https://github.com/mockito/mockito/blob/master/doc/
## Versioning
-Mockito has an automated release system, which imposed some change on how the version numbers work. While this is similar to [_semver_](http://semver.org/), there's some differences. Let's look at the following versions `1.10.19` and `2.0.5-beta` and `2.0.0` (not yet released). They follow this scheme:
+Mockito has an automated release system, which imposed some change on how the version numbers work.
+They follow this scheme:
```
-major.minor.build-tag
+major.minor.patch-tag.tagVersion
```
| number | meaning |
| ------ | ------------------------------------------------------------------------------------- |
-| major | major version, with most probably incompatible change in API and behavior |
-| minor | minor version, important enough change to bump this number |
-| build | a released build number incremented automatically when a pull request is merged |
-| tag | will probably be `-beta` or just nothing (during beta, breaking changes are expected) |
+| major | major version, backwards incompatible with the previous major version |
+| minor | minor version, backwards compatible with added features |
+| patch | patch version, small bug fixes or stylistic improvements |
+| tag | *optional* beta or RC (release candidate). See below. |
That means:
-* `2.0.0` and `2.0.5-beta` are binary incompatible with `1.10.19`.
-* `2.0.5-beta` is the fifth release beta of version `2.0.0`.
-* `2.0.5-beta` is a work in progress, api may change and may not be graduated in version `2.0.0`.
+* `2.0.0` and `2.0.0-beta.5` are binary incompatible with `1.10.19`.
+* `2.0.0-beta.5` is the fifth release beta of version `2.0.0`.
+* `2.0.0-beta.5` could be (but is not necessarily) binary incompatible with version `2.0.0`.
+* `2.0.0-RC.1` is binary compatible with release `2.0.0`.
+
+### Tags
+There are two different tags: beta or RC. Beta indicates that the version is directly generated from the master branch of the git repository.
+Beta releases are automatically published whenever we merge a pull request or push a change to the master branch.
+
+When we deem our master status worthy of a release, we publish a release candidate. The release candidate is scheduled to be officially published
+in the official release a while later. There will be no breaking changes between a release candidate and its equivalent official release.
+The only changes will include bug fixes or small updates. No additional features will be included.
## Looking for support
diff --git a/buildSrc/src/main/groovy/org/mockito/release/version/VersionBumper.java b/buildSrc/src/main/groovy/org/mockito/release/version/VersionBumper.java
index 01ed67cac5..b6f6ba8e54 100644
--- a/buildSrc/src/main/groovy/org/mockito/release/version/VersionBumper.java
+++ b/buildSrc/src/main/groovy/org/mockito/release/version/VersionBumper.java
@@ -9,17 +9,20 @@ class VersionBumper {
* Increments 'patch' element of the version of provided version, e.g. 1.0.0 -> 1.0.1
*/
String incrementVersion(String version) {
- Pattern pattern = Pattern.compile("(\\d+)\\.(\\d+)\\.(\\d+)(-(\\w+)){0,1}");
+ Pattern pattern = Pattern.compile("(\\d+)\\.(\\d+)\\.(\\d+)(-(\\w+)\\.(\\d+))?");
Matcher matcher = pattern.matcher(version);
boolean m = matcher.matches();
if (!m) {
- throw new IllegalArgumentException("Unsupported version: '" + version + "'. Examples of supported versions: 1.0.0, 1.20.123, 1.0.10-beta");
+ throw new IllegalArgumentException("Unsupported version: '" + version + "'. Examples of supported versions: 1.0.0, 1.20.123, 1.0.10-beta.3");
}
int major = Integer.parseInt(matcher.group(1));
int minor = Integer.parseInt(matcher.group(2));
int patch = Integer.parseInt(matcher.group(3));
- String postfix = matcher.group(4) != null ? matcher.group(4) : "";
- return "" + major + "." + minor + "." + (patch + 1) + postfix;
+ if (matcher.group(4) != null) {
+ int betaVersion = Integer.parseInt(matcher.group(6));
+ return "" + major + "." + minor + "." + patch + "-" + matcher.group(5) + "." + (betaVersion + 1);
+ }
+ return "" + major + "." + minor + "." + (patch + 1);
}
}
diff --git a/version.properties b/version.properties
index 3d70180266..d87a336523 100644
--- a/version.properties
+++ b/version.properties
@@ -1,2 +1,2 @@
-version=2.0.112-beta
+version=2.0.0-beta.112
mockito.testng.version=1.0
| diff --git a/buildSrc/src/test/groovy/org/mockito/release/version/VersionBumperTest.groovy b/buildSrc/src/test/groovy/org/mockito/release/version/VersionBumperTest.groovy
index db1c3d6835..b34bcda696 100644
--- a/buildSrc/src/test/groovy/org/mockito/release/version/VersionBumperTest.groovy
+++ b/buildSrc/src/test/groovy/org/mockito/release/version/VersionBumperTest.groovy
@@ -13,8 +13,9 @@ class VersionBumperTest extends Specification {
v.incrementVersion("0.0.0") == "0.0.1"
v.incrementVersion("1.10.15") == "1.10.16"
- v.incrementVersion("1.0.0-beta") == "1.0.1-beta"
- v.incrementVersion("1.10.15-beta") == "1.10.16-beta"
+ v.incrementVersion("1.0.0-beta.3") == "1.0.0-beta.4"
+ v.incrementVersion("1.10.15-beta.5") == "1.10.15-beta.6"
+ v.incrementVersion("2.0.0-RC.1") == "2.0.0-RC.2"
}
def "increments only 3 numbered versions"() {
@@ -25,6 +26,6 @@ class VersionBumperTest extends Specification {
thrown(IllegalArgumentException)
where:
- unsupported << ["1.0", "2", "1.0.0.0", "1.0.1-beta.2"]
+ unsupported << ["1.0", "2", "1.0.0.0", "1.0.1-beta"]
}
}
| val | train | 2016-08-22T09:50:54 | "2016-07-03T20:28:25Z" | TimvdLippe | train |
mockito/mockito/465_493 | mockito/mockito | mockito/mockito/465 | mockito/mockito/493 | [
"keyword_pr_to_issue"
] | 5dd0f71ae37f75f3abc9b3d9ba7ad5cb4b79f38a | 272b32bb11a41d757c535675b9bfda0fa6ffd90b | [] | [
"This can be a _oneliner_ I believe \n\n```\nif [[ $(git log --format=%B -n 1) != *\"[ci skip-release]\"* ]] ; then ./gradlew release; fi\n```\n",
"The git log command was from a travis issue as there is an intent to add the new environment variable. The command is kinda magic, so naming the variable makes it imo easier to comprehend.\n"
] | "2016-07-10T21:46:47Z" | [] | Delivery drone breaks codecov | Since the commits of the delivery drone have `[ci skip]`, there is no coverage report for that specific commit. As a result, when a pull request has as base such a commit, CodeCov reports that it could not generate a coverage report.
Maybe we can depend executing `gradle release` if the commit is from a user other than the delivery drone, to not break codecov.
| [
".travis.yml",
"dummy-commit.txt",
"gradle/release.gradle"
] | [
".travis.yml",
"dummy-commit.txt",
"gradle/release.gradle"
] | [] | diff --git a/.travis.yml b/.travis.yml
index 20b34b70df..e1b7d261d7 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -39,7 +39,9 @@ branches:
install:
- true
script:
- - ./gradlew ciBuild release
+ - TRAVIS_MESSAGE="$(git log --format=%B -n 1)"
+ - ./gradlew ciBuild
+ - if [[ $TRAVIS_MESSAGE != *"[ci skip-release]"* ]] ; then ./gradlew release; fi
after_success:
- ./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"
diff --git a/dummy-commit.txt b/dummy-commit.txt
index 39b0928f91..7ca32a7a2e 100644
--- a/dummy-commit.txt
+++ b/dummy-commit.txt
@@ -1,1 +1,1 @@
-Change this if you need a dummy commit. Push build.
+Change this if you need a dummy commit. Push build
diff --git a/gradle/release.gradle b/gradle/release.gradle
index a748bc1cd1..461d849c38 100644
--- a/gradle/release.gradle
+++ b/gradle/release.gradle
@@ -86,7 +86,7 @@ release {
releaseSteps {
String currentVersion = project.version //the version loaded when Gradle build has started
- String buildInfo = "by Travis CI build $System.env.TRAVIS_BUILD_NUMBER [ci skip]"
+ String buildInfo = "by Travis CI build $System.env.TRAVIS_BUILD_NUMBER [ci skip-release]"
MaskedArg pushTarget = new MaskedArg(value: "https://szczepiq:${System.env.GH_TOKEN}@github.com/mockito/mockito.git")
step("ensure good chunk of recent commits is pulled for release notes automation") {
@@ -197,4 +197,4 @@ TODO:
-new commits removal (git reset --hard) on all affected branches
-clean up after release:
-?
- */
\ No newline at end of file
+ */
| null | train | train | 2016-07-10T22:07:23 | "2016-06-24T11:15:49Z" | TimvdLippe | train |
mockito/mockito/482_494 | mockito/mockito | mockito/mockito/482 | mockito/mockito/494 | [
"timestamp(timedelta=54.0, similarity=0.8480688334209667)"
] | 5dd0f71ae37f75f3abc9b3d9ba7ad5cb4b79f38a | 038637612ac8abe962094d87c9cf6252f60a49dc | [
"On a related note adding a \"as of\" to the deprecated description would also be useful:\n\n``` java\n/**\n * @deprecated as of 2.0 in favor of using the enum-constant directly. This method will be removed in a future release<br> \n * E.g. instead of <code>Answers.CALLS_REAL_METHODS.get()</code> use <code>Answers.CALLS_REAL_METHODS</code> .\n */\n```\n",
"I would agree with @philwebb that this method had been made deprecated in 2.0 (-beta.2) not in 1.10.x (in fact at first it was [removed](https://github.com/mockito/mockito/commit/34f4436d988f04eaf7635b0497067ee8df7971a6) completely and one month later [restored](https://github.com/mockito/mockito/commit/32dce3ea56fb2891b54be48c16a13d2a9eb0cd33) as deprecated), but what is more important `Answers` started implementing `Answer` then. Because of that when I was fixing that issue in Spring Boot it was hard to keep code compatible with both versions at runtime (for 1.x casting using it as Answer does not work, for never 2.x `get()` is not available). In the end I had to [do](https://github.com/spring-projects/spring-boot/pull/6323/files) ugly casting through `Object` to fool the compiler. With that Spring Boot should work fine (at least with changes related to `Answers` :) ), but there could be other tools (PowerMock?) that after removing this method cannot be easily compatible with both Mockito 1.x and 2.x. IMHO it would be good to keep this method in 2.x and remove in 3.x.\n",
"Yes that seems like a good idea. Mind want to open a pull request?\n"
] | [] | "2016-07-11T13:12:41Z" | [
"bug"
] | Restore depecated Answers.get() method | Commit da5e750957b494e7fa0548bf1286d67b8b0386d5 removed the deprecated `Answers.get()` method, however the method was only deprecated in the 2.0 BETA line and never made it into a GA release. It would be helpful if the method could remain in the deprecated form in 2.0 to give people an opportunity to move away from it.
(originally raise by a Spring Boot user [here](https://github.com/spring-projects/spring-boot/pull/6323))
| [
"src/main/java/org/mockito/Answers.java"
] | [
"src/main/java/org/mockito/Answers.java"
] | [] | diff --git a/src/main/java/org/mockito/Answers.java b/src/main/java/org/mockito/Answers.java
index 5d86e9abdf..3f2ec706a1 100644
--- a/src/main/java/org/mockito/Answers.java
+++ b/src/main/java/org/mockito/Answers.java
@@ -5,11 +5,11 @@
package org.mockito;
import org.mockito.internal.stubbing.answers.CallsRealMethods;
-import org.mockito.internal.stubbing.defaultanswers.TriesToReturnSelf;
import org.mockito.internal.stubbing.defaultanswers.GloballyConfiguredAnswer;
import org.mockito.internal.stubbing.defaultanswers.ReturnsDeepStubs;
import org.mockito.internal.stubbing.defaultanswers.ReturnsMocks;
import org.mockito.internal.stubbing.defaultanswers.ReturnsSmartNulls;
+import org.mockito.internal.stubbing.defaultanswers.TriesToReturnSelf;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
@@ -24,7 +24,7 @@
* </code></pre>
* <b>This is not the full list</b> of Answers available in Mockito. Some interesting answers can be found in org.mockito.stubbing.answers package.
*/
-public enum Answers implements Answer<Object>{
+public enum Answers implements Answer<Object> {
/**
* The default configured answer of every mock.
*
@@ -78,8 +78,7 @@ public enum Answers implements Answer<Object>{
*
* @see org.mockito.Mockito#RETURNS_SELF
*/
- RETURNS_SELF(new TriesToReturnSelf())
- ;
+ RETURNS_SELF(new TriesToReturnSelf());
private final Answer<Object> implementation;
@@ -87,7 +86,16 @@ public enum Answers implements Answer<Object>{
this.implementation = implementation;
}
+ /**
+ * @deprecated Use the enum-constant directly, instead of this getter. This method will be removed in a future release<br>
+ * e.g. instead of <code>Answers.CALLS_REAL_METHODS.get()</code> use <code>Answers.CALLS_REAL_METHODS</code>.
+ */
+ @Deprecated
+ public Answer<Object> get() {
+ return this;
+ }
+
public Object answer(InvocationOnMock invocation) throws Throwable {
return implementation.answer(invocation);
- }
-}
\ No newline at end of file
+ }
+}
| null | train | train | 2016-07-10T22:07:23 | "2016-07-06T21:22:33Z" | philwebb | train |
mockito/mockito/506_507 | mockito/mockito | mockito/mockito/506 | mockito/mockito/507 | [
"timestamp(timedelta=0.0, similarity=0.8444239392740068)",
"keyword_pr_to_issue"
] | 21f80c8de824fc9a8c3d56fff029f6909d4b5b84 | 8fc9b5da2156cc8c038f2e2431459127b0901e1f | [] | [] | "2016-07-24T17:17:18Z" | [
"enhancement"
] | Improved exception message for wanted but not invoked | Currently, Mockito prints following message when specific verification fails:
```
Wanted but not invoked:
mock.simpleMethod();
-> at ....
However, there were other interactions with this mock:
mock.otherMethod();
-> at ....
mock.booleanReturningMethod();
-> at ....
```
It would be useful to print the number of invocations:
```
Wanted but not invoked:
mock.simpleMethod();
-> at ....
However, there were exactly 2 interactions with this mock:
mock.otherMethod();
-> at ....
mock.booleanReturningMethod();
-> at ....
```
| [
"src/main/java/org/mockito/internal/exceptions/Reporter.java",
"src/main/java/org/mockito/internal/reporting/Pluralizer.java"
] | [
"src/main/java/org/mockito/internal/exceptions/Reporter.java",
"src/main/java/org/mockito/internal/reporting/Pluralizer.java"
] | [
"src/test/java/org/mockito/internal/reporting/PluralizerTest.java",
"src/test/java/org/mockito/internal/verification/checkers/MissingInvocationCheckerTest.java",
"src/test/java/org/mockitousage/verification/OrdinaryVerificationPrintsAllInteractionsTest.java"
] | diff --git a/src/main/java/org/mockito/internal/exceptions/Reporter.java b/src/main/java/org/mockito/internal/exceptions/Reporter.java
index 02e9a918fb..47505bf4cb 100644
--- a/src/main/java/org/mockito/internal/exceptions/Reporter.java
+++ b/src/main/java/org/mockito/internal/exceptions/Reporter.java
@@ -8,13 +8,7 @@
import org.mockito.exceptions.base.MockitoAssertionError;
import org.mockito.exceptions.base.MockitoException;
import org.mockito.exceptions.misusing.*;
-import org.mockito.exceptions.verification.NeverWantedButInvoked;
-import org.mockito.exceptions.verification.NoInteractionsWanted;
-import org.mockito.exceptions.verification.SmartNullPointerException;
-import org.mockito.exceptions.verification.TooLittleActualInvocations;
-import org.mockito.exceptions.verification.TooManyActualInvocations;
-import org.mockito.exceptions.verification.VerificationInOrderFailure;
-import org.mockito.exceptions.verification.WantedButNotInvoked;
+import org.mockito.exceptions.verification.*;
import org.mockito.internal.debugging.LocationImpl;
import org.mockito.internal.exceptions.util.ScenarioPrinter;
import org.mockito.internal.junit.JUnitTool;
@@ -36,6 +30,7 @@
import java.util.List;
import static org.mockito.internal.reporting.Pluralizer.pluralize;
+import static org.mockito.internal.reporting.Pluralizer.were_exactly_x_interactions;
import static org.mockito.internal.util.StringJoiner.join;
/**
@@ -319,7 +314,8 @@ public static MockitoAssertionError wantedButNotInvoked(DescribedInvocation want
if (invocations.isEmpty()) {
allInvocations = "Actually, there were zero interactions with this mock.\n";
} else {
- StringBuilder sb = new StringBuilder("\nHowever, there were other interactions with this mock:\n");
+ StringBuilder sb = new StringBuilder(
+ "\nHowever, there " + were_exactly_x_interactions(invocations.size()) + " with this mock:\n");
for (DescribedInvocation i : invocations) {
sb.append(i.toString())
.append("\n")
diff --git a/src/main/java/org/mockito/internal/reporting/Pluralizer.java b/src/main/java/org/mockito/internal/reporting/Pluralizer.java
index 5e597f32ec..1e8d0e3f4b 100644
--- a/src/main/java/org/mockito/internal/reporting/Pluralizer.java
+++ b/src/main/java/org/mockito/internal/reporting/Pluralizer.java
@@ -9,4 +9,12 @@ public class Pluralizer {
public static String pluralize(int number) {
return number == 1 ? "1 time" : number + " times";
}
+
+ public static String were_exactly_x_interactions(int x) {
+ if (x == 1) {
+ return "was exactly 1 interaction";
+ } else {
+ return "were exactly " + x + " interactions";
+ }
+ }
}
| diff --git a/src/test/java/org/mockito/internal/reporting/PluralizerTest.java b/src/test/java/org/mockito/internal/reporting/PluralizerTest.java
index f35c3a8d0a..c2e1333fe9 100644
--- a/src/test/java/org/mockito/internal/reporting/PluralizerTest.java
+++ b/src/test/java/org/mockito/internal/reporting/PluralizerTest.java
@@ -12,11 +12,17 @@
public class PluralizerTest extends TestBase {
@Test
- public void shouldGetPluralizedNumber() {
- new Pluralizer();
+ public void pluralizes_number() {
assertEquals("0 times", Pluralizer.pluralize(0));
assertEquals("1 time", Pluralizer.pluralize(1));
assertEquals("2 times", Pluralizer.pluralize(2));
assertEquals("20 times", Pluralizer.pluralize(20));
}
+
+ @Test
+ public void pluralizes_interactions() {
+ assertEquals("were exactly 0 interactions", Pluralizer.were_exactly_x_interactions(0));
+ assertEquals("was exactly 1 interaction", Pluralizer.were_exactly_x_interactions(1));
+ assertEquals("were exactly 100 interactions", Pluralizer.were_exactly_x_interactions(100));
+ }
}
diff --git a/src/test/java/org/mockito/internal/verification/checkers/MissingInvocationCheckerTest.java b/src/test/java/org/mockito/internal/verification/checkers/MissingInvocationCheckerTest.java
index b5ea96b7b1..ee99529fab 100644
--- a/src/test/java/org/mockito/internal/verification/checkers/MissingInvocationCheckerTest.java
+++ b/src/test/java/org/mockito/internal/verification/checkers/MissingInvocationCheckerTest.java
@@ -55,7 +55,7 @@ public void shouldReportWantedButNotInvoked() {
exception.expect(WantedButNotInvoked.class);
exception.expectMessage("Wanted but not invoked:");
exception.expectMessage("mock.simpleMethod()");
- exception.expectMessage("However, there were other interactions with this mock:");
+ exception.expectMessage("However, there was exactly 1 interaction with this mock:");
exception.expectMessage("mock.differentMethod();");
checker.check(invocations, wanted);
diff --git a/src/test/java/org/mockitousage/verification/OrdinaryVerificationPrintsAllInteractionsTest.java b/src/test/java/org/mockitousage/verification/OrdinaryVerificationPrintsAllInteractionsTest.java
index d352fabfa1..f6245a3841 100644
--- a/src/test/java/org/mockitousage/verification/OrdinaryVerificationPrintsAllInteractionsTest.java
+++ b/src/test/java/org/mockitousage/verification/OrdinaryVerificationPrintsAllInteractionsTest.java
@@ -21,14 +21,18 @@ public class OrdinaryVerificationPrintsAllInteractionsTest extends TestBase {
@Test
public void shouldShowAllInteractionsOnMockWhenOrdinaryVerificationFail() throws Exception {
+ //given
firstInteraction();
secondInteraction();
-
+
+ verify(mock).otherMethod(); //verify 1st interaction
try {
+ //when
verify(mock).simpleMethod();
fail();
} catch (WantedButNotInvoked e) {
- assertContains("However, there were other interactions with this mock", e.getMessage());
+ //then
+ assertContains("However, there were exactly 2 interactions with this mock", e.getMessage());
assertContains("firstInteraction(", e.getMessage());
assertContains("secondInteraction(", e.getMessage());
}
| val | train | 2016-07-24T18:50:59 | "2016-07-24T17:04:33Z" | mockitoguy | train |
mockito/mockito/194_510 | mockito/mockito | mockito/mockito/194 | mockito/mockito/510 | [
"keyword_pr_to_issue",
"timestamp(timedelta=2.0, similarity=0.845934960890665)"
] | 2e1e51cf0f9178c68bcba1c97bcbe3213e002f34 | 68c7812d29e39d0c459ffd21498018d7801561e8 | [
"`any` family is currently _(at his time up to 2.0.5-beta)_ inconsistent on the way they allow or not `null`s. Type checking is ok, but `null` check behavior consistency is also important.\n",
"AnyX gramtaically tends to imply to return false for null because any\nobject is not null. I agree completely the api should be consistent.\n\nOn Sun, Apr 5, 2015, 11:54 Brice Dutheil notifications@github.com wrote:\n\n> any family is currently _(at his time up to 2.0.5-beta)_ inconsistent on\n> the way they allow or not nulls. Type checking is ok, but null check\n> behavior consistency is also important.\n> \n> ## \n> \n> Reply to this email directly or view it on GitHub\n> https://github.com/mockito/mockito/issues/194#issuecomment-89831862.\n",
"> AnyX gramtaically tends to imply to return false for null because any object is not null.\n\nI'm not anymore of sure of that. Anyway the changes introduced in this API make it inconsistent.\nThat's why I propose any validates `null`, and if not `null` then validates the type\n\nAlso on the mentioned thread _Francisco Olarte_ was proposing a `anyNotNull` family, this could clarify the behavior on `null` of these APIs.\n",
"Agreed. Any should return false for null and false for wrong type (instance\nof). Otherwise I think it would violate the principle of least surprise.\n\nOn Sun, Apr 5, 2015, 12:57 Brice Dutheil notifications@github.com wrote:\n\n> AnyX gramtaically tends to imply to return false for null because any\n> object is not null.\n> \n> I'm not anymore of sure of that. Anyway the changes introduced in this API\n> make it inconsistent.\n> That's why I propose any validates null, and if not null then validates\n> the type\n> \n> Also on the mentioned thread _Francisco Olarte_ was proposing a anyNotNull\n> family, this could clarify the behavior on null of these APIs.\n> \n> ## \n> \n> Reply to this email directly or view it on GitHub\n> https://github.com/mockito/mockito/issues/194#issuecomment-89842760.\n",
"I see anyString() ( and friends ) checking for null and anyObject() not doing it as an inconsistency potentially leading to user surprise. Object is as much of a class as String ( or other ).\n\nOther thing is I fail to see is the difference ( if there is any ) between isA(Klazz) and notNull(Klazz) ( or IsNotNull, but I see that one is a forwarder ). To me they seem they do the same, given the docs, but the code is different and I'm not familiar enough with it to assert they do the same thing. When doing DSL helper libraries I've found ( the hard way ) having slightly different names for the same thing seems a good idea initially, but leads to problem along the way, so I would vote for just having one of notNull/isNotNull ( and isA if it is functionally equivalent ).\n",
"I think there might be confusion here: @szczepiq I don't think the two of you are agreeing. @bric3 seems to be saying that `any` should match nulls and anyNotNull should exist (and presumably not match null), while you're saying that `any` should not match null.\n\nI think the problem here is that there's two use cases that currently aren't clearly separated, both of which we need to support.\n1. I don't care what the value I'm matching is _at all_, I want a very simple intuitive wildcard matcher that will match absolutely anything, and will compile with no extra effort (so no casts).\n2. I care about the type of the value that I'm matching, but no details beyond that. I want a matcher that will not match values with the wrong type.\n\nI think both of these are major common use cases. If we make any of the `anyX()` methods reject nulls, they no longer support the first case, and if we leave it as-is then they currently appear to support the 2nd case but aren't really doing so, which is where all this came from originally.\n\nI do think any API that supports use case 2 should reject nulls by default: if you're asserting specifically on the type of the value, we should push people to be clear about whether or not null is valid in the given case. I think an API for use case 1 should not reject nulls, because you want to match _everything_.\n\nThese are two quite different APIs though, and to get any kind of API consistency, we're going to need them to be separate sets of methods. I suggest:\n- `any()` - matches absolutely anything, including nulls, as a generic method returning T (as now)\n- `anyAsX()` and `anyAs(X.class)` - matches absolutely anything, including nulls, as a generic method returning X\n - This is as in 1.9, but with the names changed to make it clear that this is purely a type casting concern, not type checking, and intentionally being a bit more verbose to discourage unnecessary use.\n - Note that as of Java 8 target type inference considers method arguments, so you should be able to use `any()` in every case except choosing between overloaded methods (pretty rare?). In addition, note that Java 7's final update is this month, and then it's unsupported.\n - We'd also obviously document that users should prefer isA etc if they want to check the type, but I think it's much more obvious that `anyAsString()` isn't actually checking the value's a string (unlike `anyString()`, which did suggest that).\n- `isA/isAn(X.class)` and `isAnX()` - matches on type, rejecting nulls\n- `isNullOrAn(X.class)` and `isNullOrAnX()` - matches on type, accepting nulls\n\nI think this makes for a relatively small change, so gives fairly easy migration, but makes it clear that the `any()` methods are all just generic wildcards (for use case 1), and provides a clear set of other methods to support actual type checking and pushing users to be clear about nullability along the way (for use case 2).\n\nThe only other option I can see we might want to do is stop supporting use case 1 entirely, make everybody be much more specific about what they want, and reject nulls everywhere. I think use case one is likely to be the most common case for use argument matchers anywhere though, far more than anything else, and we definitely definitely need to support it as an intuitive easy first-class citizen.\n\nThoughts? Do people agree both use cases are common and important? Does anybody have a better solution to help us get both while keeping a sensible consistent API?\n",
"On Tue, Apr 7, 2015 at 5:12 PM, Tim Perry notifications@github.com wrote:\n\n> These are two quite different APIs though, and to get any kind of API\n> consistency, we're going to need them to be separate sets of methods. I\n> suggest:\n> - any() - matches absolutely anything, including nulls, as a generic\n> method returning T (as now)\n> - anyAsX() and anyAs(X.class) - matches absolutely anything, including\n> nulls, as a generic method returning X\n> - This is as in 1.9, but with the names changed to make it clear\n> that this is purely a type casting concern, not type checking, and\n> intentionally being a bit more verbose to discourage unnecessary use.\n> - Note that as of Java 8 target type inference considers method\n> arguments, so you should be able to use any() in every case except\n> choosing between overloaded methods (pretty rare?). In addition, note that\n> Java 7's final update is this month, and then it's unsupported.\n> - We'd also obviously document that users should prefer isA etc if\n> they want to check the type, but I think it's much more obvious that\n> anyAsString() isn't actually checking the value's a string (unlike\n> anyString(), which did suggest that).\n> - isA/isAn(X.class) and isAnX() - matches on type, rejecting nulls\n> - isNullOr(X.class) and isNullOrX() - matches on type, accepting nulls\n> \n> I think this makes for a relatively small change, so gives fairly easy\n> migration, but makes it clear that the any() methods are all just generic\n> wildcards (for use case 1), and provides a clear set of other methods to\n> support actual type checking and pushing users to be clear about\n> nullability along the way (for use case 2).\n> \n> The only other option I can see we might want to do is stop supporting use\n> case 1 entirely, make everybody be much more specific about what they want,\n> and reject nulls everywhere. I think use case one is likely to be the most\n> common case for use argument matchers anywhere though, far more than\n> anything else, and we definitely definitely need to support it as an\n> intuitive easy first-class citizen.\n> \n> Thoughts? Do people agree both use cases are common and important? Does\n> anybody have a better solution to help us get both while keeping a sensible\n> consistent API?\n\nI agree all are used and importants.\n\nI'm still struggling with the difference between `isNullOr(X.class)` and `anyAs(X.class)`. The only difference I see is if I have a class `A` with a subclass `subA`, and a class `B` with a subclass `subB`, and a couple of methods `M(A)` and `M(B)` is that `M(anyAs(subB.class))` will select `M(B)` and match on a `B`, but `M(isNullOr(subB.class)` will select it and match only on a `subB`, so I could have a broader matcher for `M(isNullOr(B.class))`.\n\nEven if this is the case, I would just suppress the `anyAs(X.class)`, as my contrived example could be better written as `anyAs(B.class)`, In which case I would rename isNullOr to any, and isA to anyNotNull. In the naming side I find `any()` natural, `anyAs` forced, as I consistently read `any(X.class)`\nas _'any thing which can be assigned to a variable of type X'_.\n\nSo I would end up with only two method names, any and `anyNotNull` with a parameterless plus a class parameter variant ( discounting typeing helpers like `anyNotNullString`), which would work:\n1. `anyNotNull`, in any variant, does not accept nulls, any does.\n2. A parameterless `any()`/`anyNotNull()` is equivalent to the same method with the declared parameter class. Note, if you can use `any[NotNull]()` in the methods there are no overloads, and the language guarantees I cannot use an incorrect type.\n\nSo, if I have a method `M(List l)`, `M(any(ArrayList.class))` would match anything which can be stored in an `ArrayList` var, subclasses and `null` included, and `anyNotNull(ArrayList.class)` will need a not null one. `M(any())` would exactly as `M(any(List.class))`. Mockito cannot check it, but I cannot write code to call `M` with a non-list argument, java is type checked. Same goes for `anyNotNull`.\n\nOTOH, if I have `M(Set s)` too, I must use `M(any(Set.class))` or `M(any(List.class))`, just to resolve the overload, although in this case the matcher type checking is superfluous.\n\nI do not see the point on `any(X.class)` not checking the type and having `isA(X.class)` which does, it seems confusing to me, so my proposal is basically zapping any of the variants. I mean, from the description, in the overloaded method, `M(any(ArrayList.class))` will select the list variant but\nmatch a call with any `List` subtype, while `isNullOr(ArrayList.class)` will only match `ArrayList`s ?. I do not see this has any real use ( the parameter type must be accessible in the test, if you want any List, use `isNullOr(List.class)`).\n\nMaybe I'm missing something, but I see `any(X.class)` redundant, better served by `isNullOr`, the rest is just naming disagreement.\n\nFrancisco Olarte.\n",
"The issue with getting rid of `anyAs(X.class)` is that we want two things:\n- A way to match an argument without checking anything about its value (any)\n- A way to match an argument and check its type (isA)\n\nI think your solution is to just use `any()` with no parameter everywhere to cover the first case, and specify the type when you want the 2nd case. That won't work, because target type inference doesn't work for method arguments in Java < 8, so it's impossible to use any() without an argument (unless the parameter is just `Object` typed).\n\nSpecifically, in Java 7 the below won't compile:\n\n``` java\nclass X {\n public bool method(List l) { ... }\n}\n\nX x = mock(X.class);\n\n// ERROR: method(java.collections.List) cannot be applied to (java.lang.Object)\nwhen (x.method(any()).thenReturn(true);\n```\n\nAnybody on Java < 8 has to specify the type every time they match anything, or it's impossible to make it compile. They can never really use `any()`; they always have to use `any(X.class)` (or equivalent). We need a way in Java 7 that you can say 'match absolutely anything please' that compiles, and I think `any(X.class)` or equivalent is the only option.\n\nIf you make that `any(X.class)` matcher check the type (as you suggest) then it no longer matches everything any more, and it becomes impossible to wildcard match everything in Java < 8 (without casting, but that would be pretty nasty)\n\nTherefore if you want to be able to both match specific types and wildcard 'match everything' in Java < 8, you have to have two separate APIs to do so. The names of those APIs need to clearly tell the user which of those two things they're doing ('match anything, but cast the matcher to make it compile' vs 'match only this type').\n\nI don't think that's avoidable. I'm very happy to take better suggestions for `anyAs(X.class)` that make it clearer it's just a convenient casting method (without making it so nasty that it stops being convenient), but that method does still need to exist I think.\n\nIn addition to all that: we'd rather the 'match a specific type' matcher didn't accept nulls by default (as your `any(List.class)` does). We need to make people opt in to matching nulls, because it's good practice, and because there's some potentially confusing behaviour there as nulls are kind of outside the type system. We also can't have the wildcard matcher reject nulls, or it's not matching everything any more. Thus, again, they need to be two different methods.\n",
"Hi Tim:\n\nOn Tue, Apr 7, 2015 at 7:37 PM, Tim Perry notifications@github.com wrote:\n\n> The issue with getting rid of anyAs(X.class) is that we want two things:\n> \n> A way to match an argument without checking anything about its value (any)\n> A way to match an argument and check its type (isA)\n> \n> I think your solution is to just use any() with no parameter everywhere to cover the first case, and specify the type when you want the 2nd case. That won't work, because target type inference doesn't work for method arguments in Java < 8, so it's impossible to use any() without an argument (unless the parameter is just Object typed).\n\nI don't think you've understood my solution. From the previously\npropossed one ( any() + anyAs(Class) + isA(Class) + isNullOrA(class) (\n- notNull(), which is in another place ) I propose to remove anyAs,\n given it does not check type, rename isA(Class) to anyNotNull(Class),\n rename isNullOrA(Class) to any(Class) and rename ( or forward )\n notNull() to anyNotNull().\n\n> Specifically, in Java 7 the below won't compile:\n> \n> class X {\n> public bool method(List l) { ... }\n> }\n> \n> X x = mock(X.class);\n> \n> // ERROR: method(java.collections.List) cannot be applied to (java.lang.Object)\n> when (x.method(any()).thenReturn(true);\n\nPerfect, in this case you use the propossed isNullOrA(Class), which I\nproposed to rename as any(Class).\n\nAlso, just grepped and got this from one of my test files:\n\n```\n AC1 = mock(AutoCaller.class);\n when(AC1.makeCall((AcCallRequest) any())).thenReturn(resp1);\n```\n\nIn case you wonder, AutoCaller is an interface with a method\n\"MakeCallResponse makeCall(AcCallRequest)\", not overloaded.\n\nI think this is clearly superior in java 7 ( I'm unable to use java 8\non those projects due to problems with the app server ). The any()\nconveys the 'i do not care, just make this compile' and the cast\nclearly says 'this is due to one of those java 7 shortcomings' to me.\n\n> Anybody on Java < 8 has to specify the type every time they match anything, or it's impossible to make it compile. They can never really use any(); they always have to use any(X.class) (or equivalent). We need a way in Java 7 that you can say 'match absolutely anything please' that compiles, and I think any(X.class) or equivalent is the only option.\n\nWhich is what I proposed, you have IsNullOrA(Class), which covers\nthis. Correct me if wrong.\n\n> If you make that any(X.class) matcher check the type (as you suggest) then it no longer matches everything any more, and it becomes impossible to wildcard match everything in Java < 8 (without casting, but that would be pretty nasty)\n\nIt is. The Method has a declared argument type of List, which means\nthe compiler will check that when you use the mock, in\nx.method(whatever) whatever implements List, so isNullOrA(List.class),\nor any(List.class) will allways match whatever, with an extra\nredundant type check.\n\n> Therefore if you want to be able to both match specific types and wildcard 'match everything' in Java < 8, you have to have two separate APIs to do so. The names of those APIs need to clearly tell the user which of those two things they're doing ('match anything, but cast the matcher to make it compile' vs 'match only this type').\n\nAs I said, I'm not knowdledgeable enough and haven't got time\npresently to dig through the sources. If any(List.class) matches when\nI pass an ArrayList to the Mock I can always wildcard by using the\ndeclared argument type.\n\n> I don't think that's avoidable. I'm very happy to take better suggestions for anyAs(X.class) that make it clearer it's just a convenient casting method (without making it so nasty that it stops being convenient), but that method does still need to exist I think.\n\nForget about my proposed renaming., With the any/anyAs/isA/IsNullOrA\nproposal, is there any case in which you must use anyAs() which cannot\nbe solved by using isNullOrA(X.class)? I think they are synonims. The\nproblem I see with anyAs as stated is that, in the previous example (\nwithout overloads ), I could code a matcher as\nwhen(x.method(anyAs(ArrayList.class))) and it shoud fire ( as it does\nnot check type ) when I do x.method(new LinkedList()). I think this is\nconfusing and asking for problem, and by making it check the type I\ncould make when(x.method(anyAss(ArrayList.class))) to catch one\nspecific thing and after that add when(x.method(anyAs(List.class)) for\na catch all in java<8, or just plain any() in >=8.\n\nMy proposal of getting rid of anyAs can be read the other way, make\nanyAs() check type and get rid of isNullOrA.\n\nRepeating my self, I proposed to get rid of anyAs(Class) as a I feel\nit seems to match something which it does not, and it cannot do\nanything which cannot be done with isNullOr(class). Name it whatever,\nis the functionality with worries me.\n\n> In addition to all that: we'd rather the 'match a specific type' matcher didn't accept nulls by default (as your any(List.class) does). We need to make people opt in to matching nulls, because it's good practice, and because there's some potentially confusing behaviour there as nulls are kind of outside the type system. We also can't have the wildcard matcher reject nulls, or it's not matching everything any more. Thus, again, they need to be two different methods.\n\nThat's another thing. What I propose is to simplify so I have two\nnames ( anyIncludingNull, anyNotNull ) which indicate wether null is\naccepted, plus two overrides, no parameters and a class parameter. The\nnull accepting behaviour is functionaly equivalent to haven just a\nname plus a boolean parameter ( notReallyAny(boolean acceptNull) +\nnotReallyAny(boolean acceptNull, Class klass) ).\n\nWhat makes me feel uncorfortable with the proposal is :\n- Too many names, I think two suffice.\n- Different names for similar methods, similar names for different\n null accepting behaviour.\n\nGiven this, I think:\n- anyIncludingNul(), anyIncludingNul(Class), anyNotNull(),\n anyNotNul(Class) cover all cases, for jdk <8 & 8 ( although\n parameterless ones are not too useful in <8 ) ( your example would be\n served by when(x.method(anyIncludingNull(List.class)) ).\n- names should be kept paired. You state opting in for nulls is good\n practice, I'll accept that without discussion. You say people should\n opt in to use them, I accept thas as a precondition. Writing\n anyIncludingNull is for me opting in.\n\nBut then, we want 'any()'. It's nice, sounds good, it is short, reads\ngood (any() in 8, I do not care, just need this to compile,\nany(List.class) in 7, I do not care, but .Well, then writing 'any(' is\nopting in to use nulls, so the class version should begin with 'any('\ntoo. I have no problem with having the null accepting versions\n'nonDefaultAcceptingNullsAnyMatcher', and the other one 'any', or\n'isA', IDEs are really good at completing, and I can easily manage a\ncouple of names, but having any, anyAs, isA, isNullOrA, and notNull\nhorrifies me.\n\nWell, that's all for today. I hope it clarifies my position.\n\nRegards.\n Francisco Olarte.\n",
"Ok, I think that mostly makes sense, although I'm not clear exactly what the full API you're proposing is that fits the requirements here. Your last paragraph seems to contradict the four methods you've suggested just above.\n\nI think you're still suggesting an `any()` method with actively different behaviour to an `any(X.class)` method though. Inconsistencies between those two are how we ended up here, because one does active type matching and the other doesn't, and you need different null matching behaviour too. In addition, you definitely need `any()` or it'll be confusing, so I don't think there's any way you can have an `any(X.class)` method that does actual matching.\n\nSounds like there is a route through though: what happens if we accept that Java 7 is on the way out, stick only to casts, and stop making the API confusing just to support now unsupported Java versions? That would give an API of:\n- `any()` - matches anything\n- `isA(X.class)` - matches things with X type, not nulls\n- `isNullOrA(X.class)` - matches things with X type, or nulls\n\nIf you're using Java 8, all is good, simple and clear. If you're using Java 7 you have to cast `any()`, but `(MyClass) any()` is clearer about what it's doing than anything else we have here, actually shorter than `any(MyClass.class)` anyway, and good IDE's will automatically suggest the cast for you too, so pretty easy to find for newbies. Null behaviour is also clear here, and we're pushing people to be explicit about whether they match nulls in all arguments they care about.\n\nHow does that sound to everybody?\n",
"Hi Tim:\n\nOn Wed, Apr 8, 2015 at 8:38 PM, Tim Perry notifications@github.com wrote:\n\n> Ok, I think that mostly makes sense, although I'm not clear exactly what the full API you're proposing is that fits the requirements here. Your last paragraph seems to contradict the four methods you've suggested just above.\n\nAny of my paragraphs may seem contradictory, but I do not know how to\nconvey the info and do not know what the exact requirements are., but\nanyway, lets go on.\n\n> I think you're still suggesting an any() method with actively different behaviour to an any(X.class) method though.\n\nIn my full sugestion not exactly, I suggested any to be the same as\nany(Object.class), ( declared parameter class really, but it could be\nimplemented this way ). It checks the passed thing is null or a\nsubclass of Object ( second check redundant, stated for completitude\n).\n\n> Inconsistencies between those two are how we ended up here, because one does active type matching and the other doesn't, and you need different null matching behaviour too. In addition, you definitely need any() or it'll be confusing, so I don't think there's any way you can have an any(X.class) method that does actual matching.\n> \n> Sounds like there is a route through though: what happens if we accept that Java 7 is on the way out, stick only to casts, and stop making the API confusing just to support now unsupported Java versions? That would give an API of:\n> any() - matches anything\n> isA(X.class) - matches things with X type, not nulls\n> isNullOrA(X.class) - matches things with X type, or nulls\n\nI'm definitely in favour of sticking to casts, as they are a standard\nlanguage feature and should be clear.\n\nNow, on your three proposed methods, you are forgetting one, which is\non another part of the current API, notNull() ( or it's cousing\nnotNull(Class), I do not know whic notNull is not declared generic\nlike any though, I think it SHOULD be for java 8 ).\n\nYou have 2 choices, 1.- accept nulls, 2.-check class, For 1 you need\neither a boolean argument or different names, for 2 you need a Class\nargument to check against. So, in your proposal you would have:\n- accept nulls, do not check class: any(), used as is in java 8,\n casted in 7 ( or for overload resolution in 8 ).\n- accept nulls, check class: isNullOrA(Class)\n- reject nulls, do not check class: notNull() ( same comments as any )\n- reject nulls, check class: isA(Class)\n\nWhich is fine dandy for me ( the naming stuff is trivial to achieve\nusing a FranciscoOlarteAdditionalMatchers helper class )\n\nBasically you can have a makeMatcher(boolean acceptNulls, Class klass\n) and then any()==makeMatcher(true, Object.class),\nisNullOrA(klass)=makeMatcher(true, klass),\nnotNull()=makeMatcher(false, Object.class),\nisA(klass)=makeMatcher(false, klass).\n\n> If you're using Java 8, all is good, simple and clear. If you're using Java 7 you have to cast any(), but (MyClass) any() is clearer about what it's doing than anything else we have here, actually shorter than any(MyClass.class) anyway, and good IDE's will automatically suggest the cast for you too, so pretty easy to find for newbies. Null behaviour is also clear here, and we're pushing people to be explicit about whether they match nulls in all arguments they care about.\n\nI think the null / check behaviour is clearer if you group them\ntogether somehow ( like I've done above ). As this gets rid of the\nconfusing (current) anyAs(Class). Also I think notNull(Class) must go,\nas what is does is served by isA(class).\n\n> How does that sound to everybody?\n\nFine for me.\n\n---------------NOT A PROPOSAL----------------\nNow, I'll explain what I proposed ( for NAMING along with some\nmotivations ). I think this discussion seems to prove it is not easily\nunderstood, this is only for reference.\n\nNote there are no functional changes with the proposal above, just\nname reorganizations as I think current names are confusing ( and I\nknow they are for me, but this is my problem and I can solve it ).\n\n0.- get rid of anyAs and notNull(class) ( served by isA and isNullOrA ).\n\n1.- any() - keep as it is.\n2.- isNullOrA(class): rename to any(class), as functionality is very\nsimilar (any()==isNullOrA(DeclaredParameterClass.class))\n3.- isA() - rename to anyNotNull ( it appears next to any() in methods\nlist, and makes the behavioural differences easy to spot. Also, if you\nhave a method any() and anyNotNull ( both being offered by\nautocomplete ) is natural to assume that any==anyIncludingNull, which\nis correct ).\n4.- notNull() - rename to anyNotNull() ( to complete the matrix ).\n\nNote: In my NAMING proposal naked any==acceptNulls, It could easily be\nreversed ( any=>anyOrNull, anyNotNull=>any, it just sounds bad to me\nthat way ( maybe because I'm used to x(Object) and x(@NonNull Object)\nand/or explicitly documenting when nulls are not allowed).\n\nExtra things:\n- anyObject() - seems to do the same thing as any, if so get rid of it\n if to avoid confusion, if not do the same as with anyString below.\n- isNull(Class) - given it can be done with (Class)isNull(), get rid\n of it. No need for a class checking version on this.\n- anyString: Confusing name with current behaviour, given any() accept\n nulls. Rename it to isAString and then, per rule 3 above, to\n anyNotNullString. THEN I would add an anyString, equal to\n isNullOrA(String.class) or any(String.class) per rule 2. Also,\n consider deleting it (note below)\n- anyInt/anyChar/...: as with anyString, in nearly all aspects.\n- anyMap/anyMapOf ( and it's friends anyList, anyCollection ): Similar\n to anyString, rename to anyNotNullMap, and then use the now free\n anyMap to build one accepting nulls.\n\nfor anyString/anyInt/..... I would consider having a basic matchers\nclass, with any/anyNotNull etc.., and a matchers derived class ( a la\nAdditionalMatchers ) and relegate all aliases to that one, so the\njavadoc for the basic matchers class concentrates on basic\nfunctionality and the one for the aliases/forwarders just states the\nequivalence ). In fact I would better put a class for just the basic\nany\\* matchers ( including just any(), any(Class), anyNotNull(),\nanyNotNull(class) and isNull(class)), another one for\neq/startsWith/... another one for the anyString and friends. Static\nimports make them easy to use in modern Java and the documentation\nwould be much easier to read (for me at least).\n\n## Hope this explains my vision.\n\nRegards.\n Francisco Olarte.\n",
"I apologize, I haven't read the entire thread. I'm still setting up my\nfamily in CA and trying to manage prioriorities.\n\nI think we have following use cases:\n1. I don't care about the parameter\n2. I care that it is not null\n3. I care about the type (implies (2))\n\nSolutions:\n\n1) any(), perhaps kill anyObject(), needs explicit casting\n2) no special API, kill isNotNull()/notNull() or just leave the\nisNotNull()/notNull(), needs explicit casting\n3) any(String.class) alias to isA(String.class) (or kill isA(...))\n\nI think it is ok if only use case 3) offers API that avoids casting. E.g.\nif the user wants to avoid casting he needs to specify the matcher better\n(which I don't think is a problem).\n\nCheers!\n\nOn Thu, Apr 9, 2015 at 2:39 AM, Francisco Olarte notifications@github.com\nwrote:\n\n> Hi Tim:\n> \n> On Wed, Apr 8, 2015 at 8:38 PM, Tim Perry notifications@github.com\n> wrote:\n> \n> > Ok, I think that mostly makes sense, although I'm not clear exactly what\n> > the full API you're proposing is that fits the requirements here. Your last\n> > paragraph seems to contradict the four methods you've suggested just above.\n> \n> Any of my paragraphs may seem contradictory, but I do not know how to\n> convey the info and do not know what the exact requirements are., but\n> anyway, lets go on.\n> \n> > I think you're still suggesting an any() method with actively different\n> > behaviour to an any(X.class) method though.\n> \n> In my full sugestion not exactly, I suggested any to be the same as\n> any(Object.class), ( declared parameter class really, but it could be\n> implemented this way ). It checks the passed thing is null or a\n> subclass of Object ( second check redundant, stated for completitude\n> ).\n> \n> > Inconsistencies between those two are how we ended up here, because one\n> > does active type matching and the other doesn't, and you need different\n> > null matching behaviour too. In addition, you definitely need any() or\n> > it'll be confusing, so I don't think there's any way you can have an\n> > any(X.class) method that does actual matching.\n> > \n> > Sounds like there is a route through though: what happens if we accept\n> > that Java 7 is on the way out, stick only to casts, and stop making the API\n> > confusing just to support now unsupported Java versions? That would give an\n> > API of:\n> > any() - matches anything\n> > isA(X.class) - matches things with X type, not nulls\n> > isNullOrA(X.class) - matches things with X type, or nulls\n> \n> I'm definitely in favour of sticking to casts, as they are a standard\n> language feature and should be clear.\n> \n> Now, on your three proposed methods, you are forgetting one, which is\n> on another part of the current API, notNull() ( or it's cousing\n> notNull(Class), I do not know whic notNull is not declared generic\n> like any though, I think it SHOULD be for java 8 ).\n> \n> You have 2 choices, 1.- accept nulls, 2.-check class, For 1 you need\n> either a boolean argument or different names, for 2 you need a Class\n> argument to check against. So, in your proposal you would have:\n> - accept nulls, do not check class: any(), used as is in java 8,\n> casted in 7 ( or for overload resolution in 8 ).\n> - accept nulls, check class: isNullOrA(Class)\n> - reject nulls, do not check class: notNull() ( same comments as any )\n> - reject nulls, check class: isA(Class)\n> \n> Which is fine dandy for me ( the naming stuff is trivial to achieve\n> using a FranciscoOlarteAdditionalMatchers helper class )\n> \n> Basically you can have a makeMatcher(boolean acceptNulls, Class klass\n> ) and then any()==makeMatcher(true, Object.class),\n> isNullOrA(klass)=makeMatcher(true, klass),\n> notNull()=makeMatcher(false, Object.class),\n> isA(klass)=makeMatcher(false, klass).\n> \n> > If you're using Java 8, all is good, simple and clear. If you're using\n> > Java 7 you have to cast any(), but (MyClass) any() is clearer about what\n> > it's doing than anything else we have here, actually shorter than\n> > any(MyClass.class) anyway, and good IDE's will automatically suggest the\n> > cast for you too, so pretty easy to find for newbies. Null behaviour is\n> > also clear here, and we're pushing people to be explicit about whether they\n> > match nulls in all arguments they care about.\n> \n> I think the null / check behaviour is clearer if you group them\n> together somehow ( like I've done above ). As this gets rid of the\n> confusing (current) anyAs(Class). Also I think notNull(Class) must go,\n> as what is does is served by isA(class).\n> \n> > How does that sound to everybody?\n> \n> Fine for me.\n> \n> ---------------NOT A PROPOSAL----------------\n> Now, I'll explain what I proposed ( for NAMING along with some\n> motivations ). I think this discussion seems to prove it is not easily\n> understood, this is only for reference.\n> \n> Note there are no functional changes with the proposal above, just\n> name reorganizations as I think current names are confusing ( and I\n> know they are for me, but this is my problem and I can solve it ).\n> \n> 0.- get rid of anyAs and notNull(class) ( served by isA and isNullOrA ).\n> \n> 1.- any() - keep as it is.\n> 2.- isNullOrA(class): rename to any(class), as functionality is very\n> similar (any()==isNullOrA(DeclaredParameterClass.class))\n> 3.- isA() - rename to anyNotNull ( it appears next to any() in methods\n> list, and makes the behavioural differences easy to spot. Also, if you\n> have a method any() and anyNotNull ( both being offered by\n> autocomplete ) is natural to assume that any==anyIncludingNull, which\n> is correct ).\n> 4.- notNull() - rename to anyNotNull() ( to complete the matrix ).\n> \n> Note: In my NAMING proposal naked any==acceptNulls, It could easily be\n> reversed ( any=>anyOrNull, anyNotNull=>any, it just sounds bad to me\n> that way ( maybe because I'm used to x(Object) and x(@NonNull Object)\n> and/or explicitly documenting when nulls are not allowed).\n> \n> Extra things:\n> - anyObject() - seems to do the same thing as any, if so get rid of it\n> if to avoid confusion, if not do the same as with anyString below.\n> - isNull(Class) - given it can be done with (Class)isNull(), get rid\n> of it. No need for a class checking version on this.\n> - anyString: Confusing name with current behaviour, given any() accept\n> nulls. Rename it to isAString and then, per rule 3 above, to\n> anyNotNullString. THEN I would add an anyString, equal to\n> isNullOrA(String.class) or any(String.class) per rule 2. Also,\n> consider deleting it (note below)\n> - anyInt/anyChar/...: as with anyString, in nearly all aspects.\n> - anyMap/anyMapOf ( and it's friends anyList, anyCollection ): Similar\n> to anyString, rename to anyNotNullMap, and then use the now free\n> anyMap to build one accepting nulls.\n> \n> for anyString/anyInt/..... I would consider having a basic matchers\n> class, with any/anyNotNull etc.., and a matchers derived class ( a la\n> AdditionalMatchers ) and relegate all aliases to that one, so the\n> javadoc for the basic matchers class concentrates on basic\n> functionality and the one for the aliases/forwarders just states the\n> equivalence ). In fact I would better put a class for just the basic\n> any\\* matchers ( including just any(), any(Class), anyNotNull(),\n> anyNotNull(class) and isNull(class)), another one for\n> eq/startsWith/... another one for the anyString and friends. Static\n> imports make them easy to use in modern Java and the documentation\n> would be much easier to read (for me at least).\n> \n> ## Hope this explains my vision.\n> \n> Regards.\n> Francisco Olarte.\n> \n> ## \n> \n> Reply to this email directly or view it on GitHub\n> https://github.com/mockito/mockito/issues/194#issuecomment-91175598.\n\n## \n\nSzczepan Faber\nFounder mockito.org; Core dev gradle.org\ntweets as @szczepiq; blogs at blog.mockito.org\n",
"Hi Szczepan:\n\nmmmm, delicious top posting...., anyway:\n\nOn Thu, Apr 9, 2015 at 3:59 PM, Szczepan Faber notifications@github.com wrote:\n\n> I think we have following use cases:\n> 1. I don't care about the parameter\n> 2. I care that it is not null\n> 3. I care about the type (implies (2))\n\nI think you lack at least one ( 4.- I care it is null, but it is\nalready served by IsNull() ( or a casted null IIRC ) ,not discussed ).\n\n> Solutions:\n> 1) any(), perhaps kill anyObject(), needs explicit casting\n> 2) no special API, kill isNotNull()/notNull() or just leave the\n> isNotNull()/notNull(), needs explicit casting\n> 3) any(String.class) alias to isA(String.class) (or kill isA(...))\n> \n> I think it is ok if only use case 3) offers API that avoids casting. E.g.\n> if the user wants to avoid casting he needs to specify the matcher better\n> (which I don't think is a problem).\n\nI don't think casting, specially in such a specialized case as\nmockiing in tests, is an issue. And J8 will avoid most of it. What I\ndislike of this is having mock.m((String)any()) accept nulls and\nmock.m(any(String.class)) reject nulls. isA sounds/reads fine to me. I\nprefer anyNotNull as name for 2 and 3 as it reads better, highlights\nthe relation with any ( they are the family of matchers which just\nchecks type, not value ), but I've reached a point where I think the\nonly form to expose a proposal is to implement it to expose how it\nlooks, which will have to wait in my case.\n\nAlso, thinking about the previous stuff, I'm beginnging to think\nIsNullOrA(Class), although it has a clear definition ( I have a\nmock.m(List), I want to match anything assignable to an ArrayList,\nwhich are null or ArrayList subclasses, so mock.m(any(ArrayList)) ),\nI'm not too sure about it's usefulness ( as I can do it with two\nmatchers, and isNull plus an isA with the same target, or use\nAdditionalMatchers.or )\n\nFrancisco Olarte.\n",
"I agree with Francisco, if we're going for casts I don't think we can have `any(String.class)` still exist, because we can't make it usefully be consistent with `any()`. I think just `isA` works fine for that case though, and I find it quite readable and clear.\n\nI do marginally prefer `notNull()` to `anyNotNull()`, just because it's shorter and simpler. I think `when(o.method(notNull(), notNull()))...` reads easier than `when(o.method(anyNotNull(), anyNotNull()))...`, and while anyNotNull makes sense in relation to any it's less clear what it does when you see it standalone. 'notNull' however is very clear indeed. It also doesn't feel quite so much like `any` and `notNull` are the same family as much as `isA/isNullOrA` are, just because `any` is kind of a special case (any + specific values are all people will probably use 1/2 the time, I expect).\n\nI also do think `isNullOrA(X.class)` does need to exist explicitly too, just because it's a common case and having to write `or(isNull(), isA(String.class))` (or `or((String) isNull(), isA(String.class))` for Java 7) everywhere is quite substantially messier and harder to parse. Internally just being an alias to that is fine though.\n\nDefinitely feels like we're getting pretty close now! One more API update then:\n- `any()` - matches anything, including nulls\n- `notNull()` matches anything, except nulls\n- `isA(X.class)` matches things of X type, except nulls\n- `isNullOrA(X.class)` matches things of X type, including nulls\n- We get rid of every other variant (`anyString()`, `isNotNull()`, etc)\n\nI think there are some other extra variants we will still need for things like generic list type checks and varargs, but those should follow on fairly cleanly from these. Thoughts?\n",
"Hi Time:\n\nOn Thu, Apr 9, 2015 at 6:34 PM, Tim Perry notifications@github.com wrote:\n\n> I agree with Francisco, if we're going for casts I don't think we can have any(String.class) still exist, because we can't make it usefully be consistent with any(). I think just isA works fine for that case though, and I find it quite readable and clear.\n\nOK.\n\n> I do marginally prefer notNull() to anyNotNull(), just because it's shorter and simpler. I think when(o.method(notNull(), notNull()))... reads easier than when(o.method(anyNotNull(), anyNotNull()))..., and while anyNotNull makes sense in relation to any it's less clear what it does when you see it standalone. 'notNull' however is very clear indeed.\n\nOK. I donot agree with the arguments but I feel voting for notNull now\nis much better than following the thread. I retract all my proposals\nfor anyNotNull.\n\n--- ASIDE---\n\n> It also doesn't feel quite so much like any and notNull are the same family as much as isA/isNullOrA are, just because any is kind of a special case (any + specific values are all people will probably use 1/2 the time, I expect).\n> I think if you place them in a square, it does. isA is NW, isNullOrA\n> is NE, any is SE, ¿ Which one goes into SW ? ( reminds me of the test\n> I did in school ).\n\nAlso, any() is like isNullOrA(Object.class), notNull() is like\nisA(Object.class).\n\nNOT A PROPOSAL/DISCUSSION on the main issue, just put here as an\nexplanation of my abandoned views.\n--- /ASIDE ---\n\n> I also do think isNullOrA(X.class) does need to exist explicitly too, just because it's a common case and having to write or(isNull(), isA(String.class)) (or or((String) isNull(), isA(String.class)) for Java 7) everywhere is quite substantially messier and harder to parse. Internally just being an alias to that is fine though.\n\nOK with it.\n\n> Definitely feels like we're getting pretty close now! One more API update then:\n> \n> any() - matches anything, including nulls\n> notNull() matches anything, except nulls\n> isA(X.class) matches things of X type, except nulls\n> isNullOrA(X.class) matches things of X type, including nulls\n> We get rid of every other variant (anyString(), isNotNull(), etc)\n> \n> I think there are some other extra variants we will still need for things like generic list type checks and varargs, but those should follow on fairly cleanly from these. Thoughts?\n\nOk. My main problem is I find current naming extremely confussing.\nOnce anyAs is gone and replaced with ( more correct IMO ) isNullOrA\nit nearly vanishes, but if variants are recovered/kept ( I would do it\nin a separate class, which could be very easily documented at the top\nand methods, otherwise they clutter the main matchers docs. Classed\nare cheap, specially in test code ) keep their name coherent to the\nimplementation. I.e., givien anyString() can (should?) be implemented\nas isA(String.class) to achieve current behaviour, name it isAString()\n(same goes if behaviour is simillar to isNullOrA) ( or zap it, I\nprefer just a longer way to do a thing than a confusing alternative )\n( I used to try to put short names to things, but since about 20 years\nago I've been progresively going to longer and clearer, typing is\neasier than thinking, YMMV ).\n\nFrancisco Olarte.\n",
"Cool, I think we're in agreement then. I'm very happy to zap lots of the extra methods like `anyString()` where Java 8 means they're not going to be useful and there's a simple easy to find alternative to them (like just casting `any()`, which most ide's will even suggest and do for you).\n\n@bric3 @szczepiq Are you two happy if I open a PR extending my previous changes to implement this API, as in my message above?\n",
"Hi @pimterry @folarte \n\nThanks for the discussion, I was also away staffed at Devoxx fr for the past week. I think there's some agreement here, I'm basically OK for these changes : \n- `<T> T any()` - matches anything, including nulls\n- `<T> T notNull()` matches anything, except nulls\n- `<T> T isA(Class<T> clazz)` matches things of `T` type but `null`\n => naming could be tweaked without the `is`, thus becoming `a(X.class)`, I understand this one is kinda bold.\n- `<T> T isNullOrA(Class<T> clazz)` matches things of `T` type including `null`\n => naming could be tweaked without the `is`, thus becoming `nullOrA(X.class)`\n- We get rid of every other variant (`anyString()`, `isNotNull(Class)`, etc)\n => there's still need for primitive matchers : `anyInt` should stay in my opinion, but this raises another issue with primitive wrappers, should they allow null, in my opinion they should not.\n\n@szczepiq Another related task would be to deprecate APIs in the 1.x line.\n",
"Happy to drop the `is` prefix, seems shorter and clearer. This might be one place where we do want an alias, for `a(String.class)` and `an(Element.class)`, as otherwise I think it's quite difficult to read.\n\n> - We get rid of every other variant (anyString(), isNotNull(Class), etc)\n> \n> => there's still need for primitive matchers : anyInt should stay in my opinion, but this raises another issue with primitive wrappers, should they allow null, in my opinion they should not.\n\nDo mean `anyInt()`, or `anInt()`? I think the conclusion of the above discussion is that we can't have an `anyInt()` method without breaking the API: either `anyInt()` actively matches the type and rejects null (confusingly inconsistent with `any()`), or it doesn't and it's confusing and people use it wrong (the current state of affairs).\n\nFor Java 8 `any()` should work everywhere I think, and for Java 7 you can use `(int) any()`. I can't easily test this right now; is there something about primitives, generics and our implementation that means this doesn't work? That's going to be a difficult problem to solve if so.\n\nFor `anInt()` on the other hand, it doesn't actually make the API inconsistent if we do add that as another method, so that's very doable. Not clear why we need it in this case either though.\n\nDo you have an example that doesn't work with this as given?\n",
"Hi Brice:\n\nOn Sun, Apr 12, 2015 at 7:55 PM, Brice Dutheil notifications@github.com wrote:\n\n> Thanks for the discussion, I was also away staffed at Devoxx fr for the past week. I think there's some agreement here, I'm basically OK for these changes :\n> \n> <T> T any() - matches anything, including nulls\n> <T> T notNull() matches anything, except nulls\n> \n> <T> T isA(Class<T> clazz) matches things of T type but null\n> => naming could be tweaked without the is, thus becoming a(X.class), I understand this one is kinda bold.\n\nI strongly disagree with naming it a or ( sorry Tim ) an. I feel they\nare too short and error prone ( and this is not COBOL, a PL/DSL is not\nEnglish ).\n\n> <T> T isNullOrA(Class<T> clazz) matches things of T type including null\n> => naming could be tweaked without the is, thus becoming nullOrA(X.class)\n\nI stil think my any/anyNotNull overrrides where superior names, but as\nthis is functionally equivalent I'll just wrap it. OK so far.\n\n> We get rid of every other variant (anyString(), isNotNull(Class), etc)\n> => there's still need for primitive matchers : anyInt should stay in my opinion, but this raises another issue with primitive wrappers, should they allow null, in my opinion they should not.\n\nI think the point of allowing nulls for primitives is a no point. If I\nhave a method mock.method(int) which I match with\nwhen(mock.method(anyInt())) it doesn't matter that the matcher\nreceives an Integer due to boxing/reflection stuff, it will never be\nnull, becuase if I do \"Integer integer = null; mock.method(integer)\"\nautounboxing will raise NPE before matchers get anything to say. And\nif there was another override mock.method(Integer), well, first this\nshould have been matched by an appropiately casted any/is\\* and second,\nit's so perverse that user deserves whatever happens there.\n\nFrancisco Olarte.\n",
"Soon. It's next in my queue :) Thank you guys for patience.\n",
"Great discussion. Thanks everybody for chipping in. Let's get this sorted out.\n\n> What I\n> dislike of this is having mock.m((String)any()) accept nulls and\n> mock.m(any(String.class)) reject nulls.\n\nI agree. There is a gotcha: given that any(SomeType.class) is most used matcher method, it will be a pain to users to upgrade to Mockito 2.0.\n\nHowever, if we tell users that any(String.class) checks type but (String) any() does not it is rather awkward message and it might confusing down the road.\n\nBy now, most users are probably used to the behavior of Mockito matchers and the pitfall is well documented ;) So there is an option to leave things as they are.\n\nRemoving any(T) pretty much means that we need to remove all matcher methods like anyString() anyList(), etc. This increases the impact on the user.\n\nI'll think about this a bit more and get back by the end of today.\n",
"BTW. what do you guys think about #246?\n",
"I think we're down to following options. Please vote or suggest other options:\n1. Shoot down any(T) and anyT() in favor of isA(). This thread seems to be converging on this approach. Consistent and clean. High impact, potential churn.\n2. Change any(T) and anyT() methods to reject nulls. Suggested by the community originally, potentially confusing down the road due to inconsistence with any(). This inconsistence becomes less of a problem with java8.\n3. Do (2) but also shoot down any() replacing it with anyObject() or anything() or '_' (ala spock ;). Not sure I like killing any() because it is neatly compact.\n4. Leave things as they are for now. Perhaps revisit for java8 support.\n",
"Hi\n \nSzczepan:\n\n> BTW. what do you guys think about #246\n> https://github.com/mockito/mockito/issues/246?\n> \n> I think it may have some problems, and be an overload abuse. If done this\n> way I would vote for having long named methods with is() being just a\n> forwarder. And I think there may be some ambiguities if overloaded is() is\n> used to test overloaded method ( i.e., when you mock m(is(String.class))\n> are you mocking m(Class c) ( as m(eq(String.class)) ) or m(String s) with\n> any string? ( It's a contrived overload, but I've seem some of these where\n> the String version takes a class name, I think OSGi has some of them ).\n> Having a long method (anyIstanceOf, equalTo, evenm, specially, isNull()\n> which I personally prefer to is(null) ( Which overload is it going to pick,\n> the Object one with a null param ) ) lets people key a little more in the\n> difficult cases and does not at too many complexity or a signigicant run\n> time for test code ( is() is just a one line forwarder, and it's javedoc\n> can be left as such which just an @link to the unoverloaded method ).\n\nRegarding readability, I'm not sure compact overloaded names are more\nreadable, they may be easier to read aloud, but you need to invoke higher\nlevel brain functions to parse it and distinguish the overload being used,\nbut maybe I'm just becoming slower.\n\nFrancisco Olarte.\n",
"Yep, I prefer option 1.\n\n#246 sounds like a good idea to me, but we should definitely market it very clearly as a convenience method (as Francisco mentions), and obviously keep the explicit methods, so people are aware they can opt in to explicitly choosing the relevant option if they need to or they're not sure what the overloading does.\n\nThe overload I'm most suspicious of is `is(T)`, just because it's most likely to be ambiguous, in practice and when trying to just think about what a line is doing. `is(null)` seems clear, `is(stringStartingWithHello)` is fine, but if I saw`when(is(100), is(String.class))`, I think my default would be to assume that the argument needed to literally be the class object. Not totally sure about that though, happy to go with it if others are happy.\n",
"Any progress on this? Are people happy for me to put together a potential PR for option 1, which it sounds like we've settled on, as something concrete to discuss?\n",
"My preference is to have the following matchers (option 1?):\n- `<T> T any()` that accepts anything including `null`. I associate _\"any\"_ to the _\"anything\"_ in my world that includes null-values and instances. It is compact and suitable for the most common cases.\n- `<T> T anyObject()` or `<T> T notNull()` reject `null` values opposite to any(). The name should indicate that null is rejected to avoid confusion about its behaviour.\n- `<T> T isA(Class<? extends T>)` reject `null` values and all values that are not a subtype of `T`, like instanceof.\n- all `any*()` and `any(T)` should be dropped cause they have different behaviour (as described before)\n",
"> 1. Shoot down any(T) and anyT() in favor of isA(). This thread seems to be converging on this approach. Consistent and clean. High impact, potential churn.\n> 2. Change any(T) and anyT() methods to reject nulls. Suggested by the community originally, potentially confusing down the road due to inconsistence with any(). This inconsistence becomes less of a problem with java8.\n> 3. Do (2) but also shoot down any() replacing it with anyObject() or anything() or '_' (ala spock ;). Not sure I like killing any() because it is neatly compact.\n> 4. Leave things as they are for now. Perhaps revisit for java8 support.\n\nLet's try to be decisive :)\n\nTim & Christian vote for option 1) I very much appreciate those votes and option 1 does have a lot of charm :)\n\nMyself, I vote for 2) because:\n- any(T) reads better (seems more fluent), is more intuitive to write than isA(). It looks good in tests.\n- it is consistent gramatically with any(), it makes the API a bit more consistent\n- java8 is very popular, people use any() for matching anything and can use any(T) for matching specific type (not null)\n- removing any(T) (options 1 and 3) seems like a churn and big impact on users without strong enough justification. It seems arbitrary that we remove the any(T) methods. E.g. myself as a user, I would not be convinced that migrating to Mockito 2.0 is a good idea because I need to fix hundreds of compilation errors due to removal fundamental API method (anyT/any(T)). Even if I make that search&replace, I'm not convinced that tests look better now. The change also hurts muscle memory and users would be finding themselves using any(T) methods, finding the code not compile, then realizing that aha! this method was removed. However, if we update the behavior of any() (option 2) we will provide very nice signal to users during the migration to 2.0. We could potentially expose bugs. Most users expect nulls to be rejected by any(T) - Mockito 2.0 will make expose tests that fail that assumption.\n\nWe don't have to agree. However, it would really cool if we were on the same page :) It would be so nice if everyone of us could stand behind decisions we make as a team.\n\nWe definitely need to make the decision!!! (if left undecided, we're effectively deciding on option 4).\n",
"I would like to suggest introducing the isA API alongside any. The latter would accept nulls while the former would rejecet them.\n\nNulls are pretty common as values so we ahould not make this more difficult than necessary. Also, tgis makes migration easier.\n",
"I already started the work on this a few days ago, and I chose to kinda follow option 2 as well, here's the plan :\n- `<T> T any()` that accepts anything including `null`. I am pondering the addition of `anything` as it is the original meaning of `any`.\n- `* any*()` / `<T> any(T)` will be aliases of `<T> isA(T)`, **this is the expected behaviour by users**, doing this will introduce the rejection of `null`, with Java 8 I saw young developer to switching to `any()` when `null` values where used instead of `anyInt`.\n\nSince we want to do a release candidate I suggest that we ship the _null safe_ `any*`, and remove the `null` check if too much people complain.\n\ncc @TimvdLippe @marcingrzejszczak @raphw @szpak \n",
"Thanks for feedback!\n\n+1 to your plan.\n\n-1 to 'anything', it feels that it does not add sufficient value. It's a\nlonger alias - not sure why would someone want to use it.\n\nOn Mon, Jul 25, 2016 at 10:10 AM Brice Dutheil notifications@github.com\nwrote:\n\n> I already started the work on this a few days ago, and I chose to kinda\n> follow option 2 as well, here's the plan :\n> - <T> T any() that accepts anything including null. I am pondering the\n> addition of anything as it is the original meaning of any.\n> - \\* any_() / <T> any(T) will be aliases of <T> isA(T), *this is the\n> expected behaviour by users_, doing this will introduce the rejection\n> of null, with Java 8 I saw young developer to switching to any() when\n> null values where used instead of anyInt.\n> \n> Since we want to do a release candidate I suggest that we ship the _null\n> safe_ any*, and remove the null check if too much people complain.\n> \n> cc @TimvdLippe https://github.com/TimvdLippe @marcingrzejszczak\n> https://github.com/marcingrzejszczak @raphw https://github.com/raphw\n> @szpak https://github.com/szpak\n> \n> —\n> You are receiving this because you were mentioned.\n> Reply to this email directly, view it on GitHub\n> https://github.com/mockito/mockito/issues/194#issuecomment-235017691,\n> or mute the thread\n> https://github.com/notifications/unsubscribe-auth/AABgp-nrLrlhKpwIt9XZjvOvBWLNnglBks5qZO3wgaJpZM4D6d0z\n> .\n",
"+1 i agree, lets try this for the RC.\n"
] | [] | "2016-07-28T17:54:59Z" | [
"refactoring",
"1.* incompatible"
] | Tweaks Matchers.any family matchers behavior | This issue is a follow up of the work started in #141 by @pimterry. Also here's an extract of a message on [this thread](https://groups.google.com/forum/#!topic/mockito/8_WGBB3Jbtk) of the mailing list :
---
The origin of these methods is they come from `anything` i.e. anything matches, later for shortness and cast avoidance the aliases grew, but the API naming thus became inconsistent with what a human would expect. So this behavior is being changed in mockito 2 beta, to be precise here's the status on these API in the version 2.0.5-beta :
- `any`, `anyObject`, `any(Class)` won't check anything (at first they were just aliases for _anything_ and for cast avoidance), `null` is a valid value
- `anyX` like `anyString` will check the arg is not `null` and that has the correct type
- `anyList` will check the argument is not null and a `List` instance
- `anyListOf` (and the likes) at the moment are just aliases to their non generic counter part like `anyList`
Note this is work in progress (started here in [#141](https://github.com/mockito/mockito/pull/141)), these new behavior can / will change in the beta phase. I'm especially wondering if the `any` family should allow `null` and if not do a type check. For example with these matchers :
- `any`, `anyObject` stay the same, they currently allow `null` and don't have to do type check anyway
- `any(Class)` currently allows `null` and doesn't do type check => allows `null` and if not checks for the given type
- `any<Collection>Of` currently doesn't allow `null` and does a type check of the collection, not elements => allows `null`, if not checks collection type, if not empty checks element type
Maybe extend/create a _symmetric_ `isA` family API that won't allow any `null` arguments.
---
| [
"src/main/java/org/mockito/ArgumentMatchers.java",
"src/main/java/org/mockito/internal/matchers/InstanceOf.java",
"src/main/java/org/mockito/internal/util/Primitives.java"
] | [
"src/main/java/org/mockito/ArgumentMatchers.java",
"src/main/java/org/mockito/internal/matchers/InstanceOf.java",
"src/main/java/org/mockito/internal/util/Primitives.java"
] | [
"src/test/java/org/mockito/internal/exceptions/stacktrace/ConditionalStackTraceFilterTest.java",
"src/test/java/org/mockito/internal/exceptions/stacktrace/StackTraceFilterTest.java",
"src/test/java/org/mockito/internal/invocation/InvocationImplTest.java",
"src/test/java/org/mockito/internal/invocation/InvocationsFinderTest.java",
"src/test/java/org/mockito/internal/matchers/InstanceOfTest.java",
"src/test/java/org/mockito/internal/util/PrimitivesTest.java",
"src/test/java/org/mockito/internal/util/TimerTest.java",
"src/test/java/org/mockito/internal/util/collections/ListUtilTest.java",
"src/test/java/org/mockitousage/IMethods.java",
"src/test/java/org/mockitousage/MethodsImpl.java",
"src/test/java/org/mockitousage/basicapi/ReplacingObjectMethodsTest.java",
"src/test/java/org/mockitousage/internal/invocation/realmethod/CleanTraceRealMethodTest.java",
"src/test/java/org/mockitousage/junitrunner/SilentRunnerTest.java",
"src/test/java/org/mockitousage/junitrunner/StrictRunnerTest.java",
"src/test/java/org/mockitousage/matchers/MatchersTest.java",
"src/test/java/org/mockitousage/matchers/MoreMatchersTest.java",
"src/test/java/org/mockitousage/matchers/NewMatchersTest.java",
"src/test/java/org/mockitousage/puzzlers/BridgeMethodPuzzleTest.java",
"src/test/java/org/mockitousage/spies/PartialMockingWithSpiesTest.java",
"src/test/java/org/mockitousage/spies/SpyingOnInterfacesTest.java",
"src/test/java/org/mockitousage/stacktrace/StackTraceFilteringTest.java",
"src/test/java/org/mockitousage/verification/DescriptiveMessagesWhenVerificationFailsTest.java",
"src/test/java/org/mockitousage/verification/PrintingVerboseTypesWithArgumentsTest.java",
"src/test/java/org/mockitoutil/Conditions.java",
"src/test/java/org/mockitoutil/JUnitResultAssert.java",
"src/test/java/org/mockitoutil/TestBase.java"
] | diff --git a/src/main/java/org/mockito/ArgumentMatchers.java b/src/main/java/org/mockito/ArgumentMatchers.java
index 8c56882540..51a3bf4993 100644
--- a/src/main/java/org/mockito/ArgumentMatchers.java
+++ b/src/main/java/org/mockito/ArgumentMatchers.java
@@ -13,10 +13,10 @@
import org.mockito.internal.matchers.apachecommons.ReflectionEquals;
import org.mockito.internal.util.Primitives;
+import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
-import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -26,379 +26,744 @@
/**
* Allow flexible verification or stubbing. See also {@link AdditionalMatchers}.
+ *
* <p>
* {@link Mockito} extends ArgumentMatchers so to get access to all matchers just import Mockito class statically.
+ *
* <pre class="code"><code class="java">
* //stubbing using anyInt() argument matcher
* when(mockedList.get(anyInt())).thenReturn("element");
- * <p>
+ *
* //following prints "element"
* System.out.println(mockedList.get(999));
- * <p>
+ *
* //you can also verify using argument matcher
* verify(mockedList).get(anyInt());
* </code></pre>
- * Scroll down to see all methods - full list of matchers.
+ *
* <p>
- * <b>Warning:</b>
+ * Since Mockito <code>any(Class)</code> and <code>anyInt</code> family matchers perform a type check, thus they won't
+ * match <code>null</code> arguments. Instead use the <code>isNull</code> matcher.
+ *
+ * <pre class="code"><code class="java">
+ * // stubbing using anyBoolean() argument matcher
+ * when(mock.dryRun(anyBoolean())).thenReturn("state");
+ *
+ * // below the stub won't match, and won't return "state"
+ * mock.dryRun(null);
+ *
+ * // either change the stub
+ * when(mock.dryRun(isNull())).thenReturn("state");
+ * mock.dryRun(null); // ok
+ *
+ * // or fix the code ;)
+ * when(mock.dryRun(anyBoolean())).thenReturn("state");
+ * mock.dryRun(true); // ok
+ *
+ * </code></pre>
+ *
+ * The same apply for verification.
+ * </p>
+ *
+ *
+ * Scroll down to see all methods - full list of matchers.
+ *
* <p>
+ * <b>Warning:</b><br/>
+ *
* If you are using argument matchers, <b>all arguments</b> have to be provided by matchers.
- * <p>
+ *
* E.g: (example shows verification but the same applies to stubbing):
+ * </p>
+ *
* <pre class="code"><code class="java">
* verify(mock).someMethod(anyInt(), anyString(), <b>eq("third argument")</b>);
* //above is correct - eq() is also an argument matcher
- * <p>
+ *
* verify(mock).someMethod(anyInt(), anyString(), <b>"third argument"</b>);
* //above is incorrect - exception will be thrown because third argument is given without argument matcher.
* </code></pre>
+ *
* <p>
* Matcher methods like <code>anyObject()</code>, <code>eq()</code> <b>do not</b> return matchers.
* Internally, they record a matcher on a stack and return a dummy value (usually null).
* This implementation is due static type safety imposed by java compiler.
* The consequence is that you cannot use <code>anyObject()</code>, <code>eq()</code> methods outside of verified/stubbed method.
- * <p>
+ * </p>
+ *
* <h1>Custom Argument ArgumentMatchers</h1>
* <p>
* It is important to understand the use cases and available options for dealing with non-trivial arguments
* <b>before</b> implementing custom argument matchers. This way, you can select the best possible approach
* for given scenario and produce highest quality test (clean and maintainable).
* Please read on in the javadoc for {@link ArgumentMatcher} to learn about approaches and see the examples.
+ * </p>
*/
@SuppressWarnings("unchecked")
public class ArgumentMatchers {
/**
- * Any <code>boolean</code> or non-null <code>Boolean</code>
+ * Matches <strong>anything</strong>, including nulls and varargs.
+ *
* <p>
* See examples in javadoc for {@link ArgumentMatchers} class
*
- * @return <code>false</code>.
+ * This is an alias of: {@link #anyObject()} and {@link #any(java.lang.Class)}
+ * </p>
+ *
+ * <p>
+ * <strong>Notes : </strong><br/>
+ * <ul>
+ * <li>For primitive types use {@link #anyChar()} family or {@link #isA(Class)} or {@link #any(Class)}.</li>
+ * <li>Since mockito 2.0 {@link #any(Class)} is not anymore an alias of this method.</li>
+ * </ul>
+ * </p>
+ *
+ * @return <code>null</code>.
+ *
+ * @see #any(Class)
+ * @see #anyObject()
+ * @see #anyVararg()
+ * @see #anyChar()
+ * @see #anyInt()
+ * @see #anyBoolean()
+ * @see #anyCollectionOf(Class)
*/
- public static boolean anyBoolean() {
- reportMatcher(new InstanceOf(Boolean.class));
- return false;
+ public static <T> T any() {
+ return anyObject();
}
/**
- * Any <code>byte</code> or non-null <code>Byte</code>.
+ * Matches anything, including <code>null</code>.
+ *
* <p>
- * See examples in javadoc for {@link ArgumentMatchers} class
+ * This is an alias of: {@link #any()} and {@link #any(java.lang.Class)}.
+ * See examples in javadoc for {@link ArgumentMatchers} class.
+ * </p>
*
- * @return <code>0</code>.
+ * @return <code>null</code>.
+ * @see #any()
+ * @see #any(Class)
+ * @see #notNull()
+ * @see #notNull(Class)
+ * @deprecated This will be removed in Mockito 3.0 (which will be java 8 only)
*/
- public static byte anyByte() {
- reportMatcher(new InstanceOf(Byte.class));
- return 0;
+ @Deprecated
+ public static <T> T anyObject() {
+ reportMatcher(Any.ANY);
+ return null;
}
/**
- * Any <code>char</code> or non-null <code>Character</code>.
+ * Matches any object of given type, excluding nulls.
+ *
* <p>
- * See examples in javadoc for {@link ArgumentMatchers} class
+ * This matcher will perform a type check with the given type, thus excluding values.
+ * See examples in javadoc for {@link ArgumentMatchers} class.
*
- * @return <code>0</code>.
+ * This is an alias of: {@link #isA(Class)}}
+ * </p>
+ *
+ * <p>
+ * Since Mockito 2.0, only allow non-null instance of <code></code>, thus <code>null</code> is not anymore a valid value.
+ * As reference are nullable, the suggested API to <strong>match</strong> <code>null</code>
+ * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito
+ * 1.x.
+ * </p>
+ *
+ * <p><strong>Notes : </strong><br/>
+ * <ul>
+ * <li>For primitive types use {@link #anyChar()} family.</li>
+ * <li>Since Mockito 2.0 this method will perform a type check thus <code>null</code> values are not authorized.</li>
+ * <li>Since mockito 2.0 {@link #any()} and {@link #anyObject()} are not anymore aliases of this method.</li>
+ * </ul>
+ * </p>
+ *
+ * @param <T> The accepted type
+ * @param type the class of the accepted type.
+ * @return <code>null</code>.
+ * @see #any()
+ * @see #anyObject()
+ * @see #anyVararg()
+ * @see #isA(Class)
+ * @see #notNull()
+ * @see #notNull(Class)
+ * @see #isNull()
+ * @see #isNull(Class)
*/
- public static char anyChar() {
- reportMatcher(new InstanceOf(Character.class));
- return 0;
+ public static <T> T any(Class<T> type) {
+ reportMatcher(new InstanceOf.VarArgAware(type, "<any " + type.getCanonicalName() + ">"));
+ return defaultValue(type);
}
/**
- * Any int or non-null Integer.
+ * <code>Object</code> argument that implements the given class.
* <p>
* See examples in javadoc for {@link ArgumentMatchers} class
*
- * @return <code>0</code>.
+ * @param <T> the accepted type.
+ * @param type the class of the accepted type.
+ * @return <code>null</code>.
+ * @see #any(Class)
*/
- public static int anyInt() {
- reportMatcher(new InstanceOf(Integer.class));
- return 0;
+ public static <T> T isA(Class<T> type) {
+ reportMatcher(new InstanceOf(type));
+ return defaultValue(type);
}
/**
- * Any <code>long</code> or non-null <code>Long</code>.
+ * Any vararg, meaning any number and values of arguments.
+ *
* <p>
- * See examples in javadoc for {@link ArgumentMatchers} class
+ * Example:
+ * <pre class="code"><code class="java">
+ * //verification:
+ * mock.foo(1, 2);
+ * mock.foo(1, 2, 3, 4);
*
- * @return <code>0</code>.
+ * verify(mock, times(2)).foo(anyVararg());
+ *
+ * //stubbing:
+ * when(mock.foo(anyVararg()).thenReturn(100);
+ *
+ * //prints 100
+ * System.out.println(mock.foo(1, 2));
+ * //also prints 100
+ * System.out.println(mock.foo(1, 2, 3, 4));
+ * </code></pre>
+ * </p>
+ *
+ * <p>
+ * See examples in javadoc for {@link ArgumentMatchers} class.
+ * </p>
+ *
+ * @return <code>null</code>.
+ * @see #any()
+ * @see #any(Class)
+ * @deprecated as of 2.0 use {@link #any()}
*/
- public static long anyLong() {
- reportMatcher(new InstanceOf(Long.class));
- return 0;
+ @Deprecated
+ public static <T> T anyVararg() {
+ any();
+ return null;
}
/**
- * Any <code>float</code> or non-null <code>Float</code>.
+ * Any <code>boolean</code> or <strong>non-null</strong> <code>Boolean</code>
+ *
* <p>
- * See examples in javadoc for {@link ArgumentMatchers} class
+ * Since Mockito 2.0, only allow valued <code>Boolean</code>, thus <code>null</code> is not anymore a valid value.
+ * As primitive wrappers are nullable, the suggested API to <strong>match</strong> <code>null</code> wrapper
+ * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito
+ * 1.x.
+ * </p>
*
- * @return <code>0</code>.
+ * <p>
+ * See examples in javadoc for {@link ArgumentMatchers} class.
+ * </p>
+ *
+ * @return <code>false</code>.
+ * @see #isNull()
+ * @see #isNull(Class)
*/
- public static float anyFloat() {
- reportMatcher(new InstanceOf(Float.class));
- return 0;
+ public static boolean anyBoolean() {
+ reportMatcher(new InstanceOf(Boolean.class, "<any boolean>"));
+ return false;
}
/**
- * Any <code>double</code> or non-null <code>Double</code>.
+ * Any <code>byte</code> or <strong>non-null</strong> <code>Byte</code>.
+ *
* <p>
- * See examples in javadoc for {@link ArgumentMatchers} class
+ * Since Mockito 2.0, only allow valued <code>Byte</code>, thus <code>null</code> is not anymore a valid value.
+ * As primitive wrappers are nullable, the suggested API to <strong>match</strong> <code>null</code> wrapper
+ * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito
+ * 1.x.
+ * </p>
+ *
+ * <p>
+ * See examples in javadoc for {@link ArgumentMatchers} class.
+ * </p>
*
* @return <code>0</code>.
+ * @see #isNull()
+ * @see #isNull(Class)
*/
- public static double anyDouble() {
- reportMatcher(new InstanceOf(Double.class));
+ public static byte anyByte() {
+ reportMatcher(new InstanceOf(Byte.class, "<any byte>"));
return 0;
}
/**
- * Any <code>short</code> or non-null <code>Short</code>.
+ * Any <code>char</code> or <strong>non-null</strong> <code>Character</code>.
+ *
* <p>
- * See examples in javadoc for {@link ArgumentMatchers} class
+ * Since Mockito 2.0, only allow valued <code>Character</code>, thus <code>null</code> is not anymore a valid value.
+ * As primitive wrappers are nullable, the suggested API to <strong>match</strong> <code>null</code> wrapper
+ * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito
+ * 1.x.
+ * </p>
+ *
+ * <p>
+ * See examples in javadoc for {@link ArgumentMatchers} class.
+ * </p>
*
* @return <code>0</code>.
+ * @see #isNull()
+ * @see #isNull(Class)
*/
- public static short anyShort() {
- reportMatcher(new InstanceOf(Short.class));
+ public static char anyChar() {
+ reportMatcher(new InstanceOf(Character.class, "<any char>"));
return 0;
}
/**
- * Matches anything, including null.
+ * Any int or <strong>non-null</strong> <code>Integer</code>.
+ *
* <p>
- * This is an alias of: {@link #any()} and {@link #any(java.lang.Class)}
+ * Since Mockito 2.0, only allow valued <code>Integer</code>, thus <code>null</code> is not anymore a valid value.
+ * As primitive wrappers are nullable, the suggested API to <strong>match</strong> <code>null</code> wrapper
+ * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito
+ * 1.x.
+ * </p>
+ *
* <p>
- * See examples in javadoc for {@link ArgumentMatchers} class
+ * See examples in javadoc for {@link ArgumentMatchers} class.
+ * </p>
*
- * @return <code>null</code>.
+ * @return <code>0</code>.
+ * @see #isNull()
+ * @see #isNull(Class)
*/
- public static <T> T anyObject() {
- reportMatcher(Any.ANY);
- return null;
+ public static int anyInt() {
+ reportMatcher(new InstanceOf(Integer.class, "<any integer>"));
+ return 0;
}
/**
- * Any vararg, meaning any number and values of arguments.
- * <p>
- * Example:
- * <pre class="code"><code class="java">
- * //verification:
- * mock.foo(1, 2);
- * mock.foo(1, 2, 3, 4);
- * <p>
- * verify(mock, times(2)).foo(anyVararg());
+ * Any <code>long</code> or <strong>non-null</strong> <code>Long</code>.
+ *
* <p>
- * //stubbing:
- * when(mock.foo(anyVararg()).thenReturn(100);
+ * Since Mockito 2.0, only allow valued <code>Long</code>, thus <code>null</code> is not anymore a valid value.
+ * As primitive wrappers are nullable, the suggested API to <strong>match</strong> <code>null</code> wrapper
+ * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito
+ * 1.x.
+ * </p>
+ *
* <p>
- * //prints 100
- * System.out.println(mock.foo(1, 2));
- * //also prints 100
- * System.out.println(mock.foo(1, 2, 3, 4));
- * </code></pre>
- * See examples in javadoc for {@link ArgumentMatchers} class
+ * See examples in javadoc for {@link ArgumentMatchers} class.
+ * </p>
*
- * @return <code>null</code>.
- * @deprecated as of 2.0 use {@link #any()}
+ * @return <code>0</code>.
+ * @see #isNull()
+ * @see #isNull(Class)
*/
- @Deprecated
- public static <T> T anyVararg() {
- any();
- return null;
+ public static long anyLong() {
+ reportMatcher(new InstanceOf(Long.class, "<any long>"));
+ return 0;
}
/**
- * Matches any object, including nulls
- * <p>
- * This method doesn't do type checks with the given parameter, it is only there
- * to avoid casting in your code. This might however change (type checks could
- * be added) in a future major release.
- * <p>
- * See examples in javadoc for {@link ArgumentMatchers} class
+ * Any <code>float</code> or <strong>non-null</strong> <code>Float</code>.
+ *
* <p>
- * This is an alias of: {@link #any()} and {@link #anyObject()}
+ * Since Mockito 2.0, only allow valued <code>Float</code>, thus <code>null</code> is not anymore a valid value.
+ * As primitive wrappers are nullable, the suggested API to <strong>match</strong> <code>null</code> wrapper
+ * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito
+ * 1.x.
+ * </p>
+ *
* <p>
+ * See examples in javadoc for {@link ArgumentMatchers} class.
+ * </p>
*
- * @return <code>null</code>.
+ * @return <code>0</code>.
+ * @see #isNull()
+ * @see #isNull(Class)
*/
- public static <T> T any(Class<T> clazz) {
- reportMatcher(Any.ANY);
- return defaultValue(clazz);
+ public static float anyFloat() {
+ reportMatcher(new InstanceOf(Float.class, "<any float>"));
+ return 0;
}
/**
- * Matches anything, including nulls and varargs
+ * Any <code>double</code> or <strong>non-null</strong> <code>Double</code>.
+ *
* <p>
- * Shorter alias to {@link ArgumentMatchers#anyObject()}
+ * Since Mockito 2.0, only allow valued <code>Double</code>, thus <code>null</code> is not anymore a valid value.
+ * As primitive wrappers are nullable, the suggested API to <strong>match</strong> <code>null</code> wrapper
+ * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito
+ * 1.x.
+ * </p>
+ *
* <p>
- * See examples in javadoc for {@link ArgumentMatchers} class
+ * See examples in javadoc for {@link ArgumentMatchers} class.
+ * </p>
+ *
+ * @return <code>0</code>.
+ * @see #isNull()
+ * @see #isNull(Class)
+ */
+ public static double anyDouble() {
+ reportMatcher(new InstanceOf(Double.class, "<any double>"));
+ return 0;
+ }
+
+ /**
+ * Any <code>short</code> or <strong>non-null</strong> <code>Short</code>.
+ *
* <p>
- * This is an alias of: {@link #anyObject()} and {@link #any(java.lang.Class)}
+ * Since Mockito 2.0, only allow valued <code>Short</code>, thus <code>null</code> is not anymore a valid value.
+ * As primitive wrappers are nullable, the suggested API to <strong>match</strong> <code>null</code> wrapper
+ * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito
+ * 1.x.
+ * </p>
+ *
* <p>
+ * See examples in javadoc for {@link ArgumentMatchers} class.
+ * </p>
*
- * @return <code>null</code>.
+ * @return <code>0</code>.
+ * @see #isNull()
+ * @see #isNull(Class)
*/
- public static <T> T any() {
- return anyObject();
+ public static short anyShort() {
+ reportMatcher(new InstanceOf(Short.class, "<any short>"));
+ return 0;
}
/**
- * Any non-null <code>String</code>
+ * Any <strong>non-null</strong> <code>String</code>
+ *
* <p>
- * See examples in javadoc for {@link ArgumentMatchers} class
+ * Since Mockito 2.0, only allow non-null <code>String</code>.
+ * As this is a nullable reference, the suggested API to <strong>match</strong> <code>null</code> wrapper
+ * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito
+ * 1.x.
+ * </p>
+ *
+ * <p>
+ * See examples in javadoc for {@link ArgumentMatchers} class.
+ * </p>
*
* @return empty String ("")
+ * @see #isNull()
+ * @see #isNull(Class)
*/
public static String anyString() {
- reportMatcher(new InstanceOf(String.class));
+ reportMatcher(new InstanceOf(String.class, "<any string>"));
return "";
}
/**
- * Any non-null <code>List</code>.
+ * Any <strong>non-null</strong> <code>List</code>.
+ *
* <p>
- * See examples in javadoc for {@link ArgumentMatchers} class
+ * Since Mockito 2.0, only allow non-null <code>List</code>.
+ * As this is a nullable reference, the suggested API to <strong>match</strong> <code>null</code> wrapper
+ * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito
+ * 1.x.
+ * </p>
+ *
+ * <p>
+ * See examples in javadoc for {@link ArgumentMatchers} class.
+ * </p>
*
* @return empty List.
+ * @see #anyListOf(Class)
+ * @see #isNull()
+ * @see #isNull(Class)
*/
public static List anyList() {
- reportMatcher(new InstanceOf(List.class));
- return new LinkedList();
+ reportMatcher(new InstanceOf(List.class, "<any List>"));
+ return new ArrayList(0);
}
/**
- * Generic friendly alias to {@link ArgumentMatchers#anyList()}.
- * It's an alternative to @SuppressWarnings("unchecked") to keep code clean of compiler warnings.
+ * Any <strong>non-null</strong> <code>List</code>.
+ *
+ * Generic friendly alias to {@link ArgumentMatchers#anyList()}. It's an alternative to
+ * <code>@SuppressWarnings("unchecked")</code> to keep code clean of compiler warnings.
+ *
* <p>
- * Any non-null <code>List</code>.
+ * This method doesn't do type checks of the list content with the given type parameter, it is only there
+ * to avoid casting in the code.
+ * </p>
+ *
* <p>
- * This method doesn't do type checks with the given parameter, it is only there
- * to avoid casting in your code. This might however change (type checks could
- * be added) in a future major release.
+ * Since Mockito 2.0, only allow non-null <code>List</code>.
+ * As this is a nullable reference, the suggested API to <strong>match</strong> <code>null</code> wrapper
+ * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito
+ * 1.x.
+ * </p>
+ *
* <p>
- * See examples in javadoc for {@link ArgumentMatchers} class
+ * See examples in javadoc for {@link ArgumentMatchers} class.
+ * </p>
*
* @param clazz Type owned by the list to avoid casting
* @return empty List.
+ * @see #anyList()
+ * @see #isNull()
+ * @see #isNull(Class)
+ * @deprecated With Java 8 this method will be removed in Mockito 3.0. This method is only used for generic
+ * friendliness to avoid casting, this is not anymore needed in Java 8.
*/
public static <T> List<T> anyListOf(Class<T> clazz) {
return anyList();
}
/**
- * Any non-null <code>Set</code>.
+ * Any <strong>non-null</strong> <code>Set</code>.
+ *
* <p>
- * See examples in javadoc for {@link ArgumentMatchers} class
+ * Since Mockito 2.0, only allow non-null <code>Set</code>.
+ * As this is a nullable reference, the suggested API to <strong>match</strong> <code>null</code> wrapper
+ * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito
+ * 1.x.
+ * </p>
+ *
+ * <p>
+ * See examples in javadoc for {@link ArgumentMatchers} class.
+ * </p>
*
* @return empty Set
+ * @see #anySetOf(Class)
+ * @see #isNull()
+ * @see #isNull(Class)
*/
public static Set anySet() {
- reportMatcher(new InstanceOf(Set.class));
- return new HashSet();
+ reportMatcher(new InstanceOf(Set.class, "<any set>"));
+ return new HashSet(0);
}
/**
+ * Any <strong>non-null</strong> <code>Set</code>.
+ *
+ * <p>
* Generic friendly alias to {@link ArgumentMatchers#anySet()}.
- * It's an alternative to @SuppressWarnings("unchecked") to keep code clean of compiler warnings.
+ * It's an alternative to <code>@SuppressWarnings("unchecked")</code> to keep code clean of compiler warnings.
+ * </p>
+ *
* <p>
- * Any non-null <code>Set</code>.
+ * This method doesn't do type checks of the set content with the given type parameter, it is only there
+ * to avoid casting in the code.
+ * </p>
+ *
* <p>
- * This method doesn't do type checks with the given parameter, it is only there
- * to avoid casting in your code. This might however change (type checks could
- * be added) in a future major release.
+ * Since Mockito 2.0, only allow non-null <code>Set</code>.
+ * As this is a nullable reference, the suggested API to <strong>match</strong> <code>null</code> wrapper
+ * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito
+ * 1.x.
+ * </p>
+ *
* <p>
- * See examples in javadoc for {@link ArgumentMatchers} class
+ * See examples in javadoc for {@link ArgumentMatchers} class.
+ * </p>
*
* @param clazz Type owned by the Set to avoid casting
* @return empty Set
+ * @see #anySet()
+ * @see #isNull()
+ * @see #isNull(Class)
+ * @deprecated With Java 8 this method will be removed in Mockito 3.0. This method is only used for generic
+ * friendliness to avoid casting, this is not anymore needed in Java 8.
*/
public static <T> Set<T> anySetOf(Class<T> clazz) {
return anySet();
}
/**
- * Any non-null <code>Map</code>.
+ * Any <strong>non-null</strong> <code>Map</code>.
+ *
* <p>
- * See examples in javadoc for {@link ArgumentMatchers} class
+ * Since Mockito 2.0, only allow non-null <code>Map</code>.
+ * As this is a nullable reference, the suggested API to <strong>match</strong> <code>null</code> wrapper
+ * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito
+ * 1.x.
+ * </p>
+ *
+ * <p>
+ * See examples in javadoc for {@link ArgumentMatchers} class.
+ * </p>
*
* @return empty Map.
+ * @see #anyMapOf(Class, Class)
+ * @see #isNull()
+ * @see #isNull(Class)
*/
public static Map anyMap() {
- reportMatcher(new InstanceOf(Map.class));
- return new HashMap();
+ reportMatcher(new InstanceOf(Map.class, "<any map>"));
+ return new HashMap(0);
}
/**
+ * Any <strong>non-null</strong> <code>Map</code>.
+ *
+ * <p>
* Generic friendly alias to {@link ArgumentMatchers#anyMap()}.
- * It's an alternative to @SuppressWarnings("unchecked") to keep code clean of compiler warnings.
+ * It's an alternative to <code>@SuppressWarnings("unchecked")</code> to keep code clean of compiler warnings.
+ * </p>
+ *
* <p>
- * Any non-null <code>Map</code>.
+ * This method doesn't do type checks of the map content with the given type parameter, it is only there
+ * to avoid casting in the code.
+ * </p>
+ *
* <p>
- * This method doesn't do type checks with the given parameter, it is only there
- * to avoid casting in your code. This might however change (type checks could
- * be added) in a future major release.
+ * Since Mockito 2.0, only allow non-null <code>Map</code>.
+ * As this is a nullable reference, the suggested API to <strong>match</strong> <code>null</code> wrapper
+ * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito
+ * 1.x.
+ * </p>
+ *
* <p>
- * See examples in javadoc for {@link ArgumentMatchers} class
+ * See examples in javadoc for {@link ArgumentMatchers} class.
+ * </p>
*
* @param keyClazz Type of the map key to avoid casting
* @param valueClazz Type of the value to avoid casting
* @return empty Map.
+ * @see #anyMap()
+ * @see #isNull()
+ * @see #isNull(Class)
+ * @deprecated With Java 8 this method will be removed in Mockito 3.0. This method is only used for generic
+ * friendliness to avoid casting, this is not anymore needed in Java 8.
*/
public static <K, V> Map<K, V> anyMapOf(Class<K> keyClazz, Class<V> valueClazz) {
return anyMap();
}
/**
- * Any non-null <code>Collection</code>.
+ * Any <strong>non-null</strong> <code>Collection</code>.
+ *
* <p>
- * See examples in javadoc for {@link ArgumentMatchers} class
+ * Since Mockito 2.0, only allow non-null <code>Collection</code>.
+ * As this is a nullable reference, the suggested API to <strong>match</strong> <code>null</code>
+ * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito
+ * 1.x.
+ * </p>
+ *
+ * <p>
+ * See examples in javadoc for {@link ArgumentMatchers} class.
+ * </p>
*
* @return empty Collection.
+ * @see #anyCollectionOf(Class)
+ * @see #isNull()
+ * @see #isNull(Class)
*/
public static Collection anyCollection() {
- reportMatcher(new InstanceOf(Collection.class));
- return new LinkedList();
+ reportMatcher(new InstanceOf(Collection.class, "<any collection>"));
+ return new ArrayList(0);
}
/**
+ * Any <strong>non-null</strong> <code>Collection</code>.
+ *
+ * <p>
* Generic friendly alias to {@link ArgumentMatchers#anyCollection()}.
- * It's an alternative to @SuppressWarnings("unchecked") to keep code clean of compiler warnings.
+ * It's an alternative to <code>@SuppressWarnings("unchecked")</code> to keep code clean of compiler warnings.
+ * </p>
+ *
* <p>
- * Any non-null <code>Collection</code>.
+ * This method doesn't do type checks of the collection content with the given type parameter, it is only there
+ * to avoid casting in the code.
+ * </p>
+ *
* <p>
- * This method doesn't do type checks with the given parameter, it is only there
- * to avoid casting in your code. This might however change (type checks could
- * be added) in a future major release.
+ * Since Mockito 2.0, only allow non-null <code>Collection</code>.
+ * As this is a nullable reference, the suggested API to <strong>match</strong> <code>null</code>
+ * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito
+ * 1.x.
+ * </p>
+ *
* <p>
- * See examples in javadoc for {@link ArgumentMatchers} class
+ * See examples in javadoc for {@link ArgumentMatchers} class.
+ * </p>
*
* @param clazz Type owned by the collection to avoid casting
* @return empty Collection.
+ * @see #anyCollection()
+ * @see #isNull()
+ * @see #isNull(Class)
+ * @deprecated With Java 8 this method will be removed in Mockito 3.0. This method is only used for generic
+ * friendliness to avoid casting, this is not anymore needed in Java 8.
*/
public static <T> Collection<T> anyCollectionOf(Class<T> clazz) {
return anyCollection();
}
/**
- * <code>Object</code> argument that implements the given class.
+ * Any <strong>non-null</strong> <code>Iterable</code>.
+ *
* <p>
- * See examples in javadoc for {@link ArgumentMatchers} class
+ * Since Mockito 2.0, only allow non-null <code>Iterable</code>.
+ * As this is a nullable reference, the suggested API to <strong>match</strong> <code>null</code>
+ * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito
+ * 1.x.
+ * </p>
*
- * @param <T> the accepted type.
- * @param type the class of the accepted type.
- * @return <code>null</code>.
+ * <p>
+ * See examples in javadoc for {@link ArgumentMatchers} class.
+ * </p>
+ *
+ * @return empty Iterable.
+ * @see #anyIterableOf(Class)
+ * @see #isNull()
+ * @see #isNull(Class)
+ * @since 2.0.0
*/
- public static <T> T isA(Class<T> type) {
- reportMatcher(new InstanceOf(type));
+ public static Collection anyIterable() {
+ reportMatcher(new InstanceOf(Iterable.class, "<any iterable>"));
+ return new ArrayList(0);
+ }
- return defaultValue(type);
+ /**
+ * Any <strong>non-null</strong> <code>Iterable</code>.
+ *
+ * <p>
+ * Generic friendly alias to {@link ArgumentMatchers#anyIterable()}.
+ * It's an alternative to <code>@SuppressWarnings("unchecked")</code> to keep code clean of compiler warnings.
+ * </p>
+ *
+ * <p>
+ * This method doesn't do type checks of the iterable content with the given type parameter, it is only there
+ * to avoid casting in the code.
+ * </p>
+ *
+ * <p>
+ * Since Mockito 2.0, only allow non-null <code>String</code>.
+ * As strings are nullable reference, the suggested API to <strong>match</strong> <code>null</code> wrapper
+ * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito
+ * 1.x.
+ * </p>
+ *
+ * <p>
+ * See examples in javadoc for {@link ArgumentMatchers} class.
+ * </p>
+ *
+ * @param clazz Type owned by the collection to avoid casting
+ * @return empty Iterable.
+ * @see #anyIterable()
+ * @see #isNull()
+ * @see #isNull(Class)
+ * @since 2.0.0
+ * @deprecated With Java 8 this method will be removed in Mockito 3.0. This method is only used for generic
+ * friendliness to avoid casting, this is not anymore needed in Java 8.
+ */
+ public static <T> Iterable<T> anyIterableOf(Class<T> clazz) {
+ return anyIterable();
}
+
+
/**
* <code>boolean</code> argument that is equal to the given value.
+ *
* <p>
* See examples in javadoc for {@link ArgumentMatchers} class
+ * </p>
*
* @param value the given value.
* @return <code>0</code>.
@@ -410,8 +775,10 @@ public static boolean eq(boolean value) {
/**
* <code>byte</code> argument that is equal to the given value.
+ *
* <p>
* See examples in javadoc for {@link ArgumentMatchers} class
+ * </p>
*
* @param value the given value.
* @return <code>0</code>.
@@ -423,8 +790,10 @@ public static byte eq(byte value) {
/**
* <code>char</code> argument that is equal to the given value.
+ *
* <p>
* See examples in javadoc for {@link ArgumentMatchers} class
+ * </p>
*
* @param value the given value.
* @return <code>0</code>.
@@ -436,8 +805,10 @@ public static char eq(char value) {
/**
* <code>double</code> argument that is equal to the given value.
+ *
* <p>
* See examples in javadoc for {@link ArgumentMatchers} class
+ * </p>
*
* @param value the given value.
* @return <code>0</code>.
@@ -449,8 +820,10 @@ public static double eq(double value) {
/**
* <code>float</code> argument that is equal to the given value.
+ *
* <p>
* See examples in javadoc for {@link ArgumentMatchers} class
+ * </p>
*
* @param value the given value.
* @return <code>0</code>.
@@ -462,8 +835,10 @@ public static float eq(float value) {
/**
* <code>int</code> argument that is equal to the given value.
+ *
* <p>
* See examples in javadoc for {@link ArgumentMatchers} class
+ * </p>
*
* @param value the given value.
* @return <code>0</code>.
@@ -475,8 +850,10 @@ public static int eq(int value) {
/**
* <code>long</code> argument that is equal to the given value.
+ *
* <p>
* See examples in javadoc for {@link ArgumentMatchers} class
+ * </p>
*
* @param value the given value.
* @return <code>0</code>.
@@ -501,8 +878,10 @@ public static short eq(short value) {
/**
* Object argument that is equal to the given value.
+ *
* <p>
* See examples in javadoc for {@link ArgumentMatchers} class
+ * </p>
*
* @param value the given value.
* @return <code>null</code>.
@@ -517,16 +896,22 @@ public static <T> T eq(T value) {
/**
* Object argument that is reflection-equal to the given value with support for excluding
* selected fields from a class.
+ *
* <p>
* This matcher can be used when equals() is not implemented on compared objects.
* Matcher uses java reflection API to compare fields of wanted and actual object.
+ * </p>
+ *
* <p>
- * Works similarly to EqualsBuilder.reflectionEquals(this, other, exlucdeFields) from
+ * Works similarly to <code>EqualsBuilder.reflectionEquals(this, other, exlucdeFields)</code> from
* apache commons library.
* <p>
* <b>Warning</b> The equality check is shallow!
+ * </p>
+ *
* <p>
* See examples in javadoc for {@link ArgumentMatchers} class
+ * </p>
*
* @param value the given value.
* @param excludeFields fields to exclude, if field does not exist it is ignored.
@@ -539,8 +924,10 @@ public static <T> T refEq(T value, String... excludeFields) {
/**
* Object argument that is the same as the given value.
+ *
* <p>
* See examples in javadoc for {@link ArgumentMatchers} class
+ * </p>
*
* @param <T> the type of the object, it is passed through to prevent casts.
* @param value the given value.
@@ -555,83 +942,123 @@ public static <T> T same(T value) {
/**
* <code>null</code> argument.
+ *
* <p>
* See examples in javadoc for {@link ArgumentMatchers} class
+ * </p>
*
* @return <code>null</code>.
+ * @see #isNull(Class)
+ * @see #isNotNull()
+ * @see #isNotNull(Class)
*/
- public static Object isNull() {
+ public static <T> T isNull() {
reportMatcher(Null.NULL);
return null;
}
/**
* <code>null</code> argument.
+ *
+ * <p>
* The class argument is provided to avoid casting.
+ * </p>
+ *
* <p>
* See examples in javadoc for {@link ArgumentMatchers} class
+ * </p>
*
* @param clazz Type to avoid casting
* @return <code>null</code>.
+ * @see #isNull()
+ * @see #isNotNull()
+ * @see #isNotNull(Class)
+ * @deprecated With Java 8 this method will be removed in Mockito 3.0. This method is only used for generic
+ * friendliness to avoid casting, this is not anymore needed in Java 8.
*/
public static <T> T isNull(Class<T> clazz) {
- reportMatcher(Null.NULL);
- return null;
+ return isNull();
}
/**
* Not <code>null</code> argument.
+ *
* <p>
- * alias to {@link ArgumentMatchers#isNotNull()}
+ * Alias to {@link ArgumentMatchers#isNotNull()}
+ * </p>
+ *
* <p>
* See examples in javadoc for {@link ArgumentMatchers} class
+ * </p>
*
* @return <code>null</code>.
*/
- public static Object notNull() {
+ public static <T> T notNull() {
reportMatcher(NotNull.NOT_NULL);
return null;
}
/**
* Not <code>null</code> argument, not necessary of the given class.
+ *
+ * <p>
* The class argument is provided to avoid casting.
+ *
+ * Alias to {@link ArgumentMatchers#isNotNull(Class)}
* <p>
- * alias to {@link ArgumentMatchers#isNotNull(Class)}
+ *
* <p>
* See examples in javadoc for {@link ArgumentMatchers} class
+ * </p>
*
* @param clazz Type to avoid casting
* @return <code>null</code>.
+ * @see #isNotNull()
+ * @see #isNull()
+ * @see #isNull(Class)
+ * @deprecated With Java 8 this method will be removed in Mockito 3.0. This method is only used for generic
+ * friendliness to avoid casting, this is not anymore needed in Java 8.
*/
public static <T> T notNull(Class<T> clazz) {
- reportMatcher(NotNull.NOT_NULL);
- return null;
+ return notNull();
}
/**
* Not <code>null</code> argument.
+ *
* <p>
- * alias to {@link ArgumentMatchers#notNull()}
+ * Alias to {@link ArgumentMatchers#notNull()}
+ * </p>
+ *
* <p>
* See examples in javadoc for {@link ArgumentMatchers} class
+ * </p>
*
* @return <code>null</code>.
+ * @see #isNotNull(Class)
+ * @see #isNull()
+ * @see #isNull(Class)
*/
- public static Object isNotNull() {
+ public static <T> T isNotNull() {
return notNull();
}
/**
* Not <code>null</code> argument, not necessary of the given class.
- * The class argument is provided to avoid casting.
+ *
* <p>
- * alias to {@link ArgumentMatchers#notNull(Class)}
+ * The class argument is provided to avoid casting.
+ * Alias to {@link ArgumentMatchers#notNull(Class)}
+ * </p>
+ *
* <p>
* See examples in javadoc for {@link ArgumentMatchers} class
+ * </p>
*
* @param clazz Type to avoid casting
* @return <code>null</code>.
+ * @deprecated With Java 8 this method will be removed in Mockito 3.0. This method is only used for generic
+ * friendliness to avoid casting, this is not anymore needed in Java 8.
*/
public static <T> T isNotNull(Class<T> clazz) {
return notNull(clazz);
@@ -691,13 +1118,19 @@ public static String startsWith(String prefix) {
/**
* Allows creating custom argument matchers.
+ *
+ * <p>
* This API has changed in 2.0, please read {@link ArgumentMatcher} for rationale and migration guide.
* <b>NullPointerException</b> auto-unboxing caveat is described below.
+ * </p>
+ *
* <p>
* It is important to understand the use cases and available options for dealing with non-trivial arguments
* <b>before</b> implementing custom argument matchers. This way, you can select the best possible approach
* for given scenario and produce highest quality test (clean and maintainable).
* Please read the documentation for {@link ArgumentMatcher} to learn about approaches and see the examples.
+ * </p>
+ *
* <p>
* <b>NullPointerException</b> auto-unboxing caveat.
* In rare cases when matching primitive parameter types you <b>*must*</b> use relevant intThat(), floatThat(), etc. method.
@@ -705,8 +1138,11 @@ public static String startsWith(String prefix) {
* Due to how java works we don't really have a clean way of detecting this scenario and protecting the user from this problem.
* Hopefully, the javadoc describes the problem and solution well.
* If you have an idea how to fix the problem, let us know via the mailing list or the issue tracker.
+ * </p>
+ *
* <p>
* See examples in javadoc for {@link ArgumentMatcher} class
+ * </p>
*
* @param matcher decides whether argument matches
* @return <code>null</code>.
@@ -718,6 +1154,7 @@ public static <T> T argThat(ArgumentMatcher<T> matcher) {
/**
* Allows creating custom <code>char</code> argument matchers.
+ *
* Note that {@link #argThat} will not work with primitive <code>char</code> matchers due to <code>NullPointerException</code> auto-unboxing caveat.
* <p>
* See examples in javadoc for {@link ArgumentMatchers} class
@@ -732,6 +1169,7 @@ public static char charThat(ArgumentMatcher<Character> matcher) {
/**
* Allows creating custom <code>boolean</code> argument matchers.
+ *
* Note that {@link #argThat} will not work with primitive <code>boolean</code> matchers due to <code>NullPointerException</code> auto-unboxing caveat.
* <p>
* See examples in javadoc for {@link ArgumentMatchers} class
@@ -746,6 +1184,7 @@ public static boolean booleanThat(ArgumentMatcher<Boolean> matcher) {
/**
* Allows creating custom <code>byte</code> argument matchers.
+ *
* Note that {@link #argThat} will not work with primitive <code>byte</code> matchers due to <code>NullPointerException</code> auto-unboxing caveat.
* <p>
* See examples in javadoc for {@link ArgumentMatchers} class
@@ -760,6 +1199,7 @@ public static byte byteThat(ArgumentMatcher<Byte> matcher) {
/**
* Allows creating custom <code>short</code> argument matchers.
+ *
* Note that {@link #argThat} will not work with primitive <code>short</code> matchers due to <code>NullPointerException</code> auto-unboxing caveat.
* <p>
* See examples in javadoc for {@link ArgumentMatchers} class
@@ -774,6 +1214,7 @@ public static short shortThat(ArgumentMatcher<Short> matcher) {
/**
* Allows creating custom <code>int</code> argument matchers.
+ *
* Note that {@link #argThat} will not work with primitive <code>int</code> matchers due to <code>NullPointerException</code> auto-unboxing caveat.
* <p>
* See examples in javadoc for {@link ArgumentMatchers} class
@@ -788,6 +1229,7 @@ public static int intThat(ArgumentMatcher<Integer> matcher) {
/**
* Allows creating custom <code>long</code> argument matchers.
+ *
* Note that {@link #argThat} will not work with primitive <code>long</code> matchers due to <code>NullPointerException</code> auto-unboxing caveat.
* <p>
* See examples in javadoc for {@link ArgumentMatchers} class
@@ -802,6 +1244,7 @@ public static long longThat(ArgumentMatcher<Long> matcher) {
/**
* Allows creating custom <code>float</code> argument matchers.
+ *
* Note that {@link #argThat} will not work with primitive <code>float</code> matchers due to <code>NullPointerException</code> auto-unboxing caveat.
* <p>
* See examples in javadoc for {@link ArgumentMatchers} class
@@ -816,6 +1259,7 @@ public static float floatThat(ArgumentMatcher<Float> matcher) {
/**
* Allows creating custom <code>double</code> argument matchers.
+ *
* Note that {@link #argThat} will not work with primitive <code>double</code> matchers due to <code>NullPointerException</code> auto-unboxing caveat.
* <p>
* See examples in javadoc for {@link ArgumentMatchers} class
diff --git a/src/main/java/org/mockito/internal/matchers/InstanceOf.java b/src/main/java/org/mockito/internal/matchers/InstanceOf.java
index c315c34ee4..2876aa24d0 100644
--- a/src/main/java/org/mockito/internal/matchers/InstanceOf.java
+++ b/src/main/java/org/mockito/internal/matchers/InstanceOf.java
@@ -6,6 +6,7 @@
package org.mockito.internal.matchers;
import org.mockito.ArgumentMatcher;
+import org.mockito.internal.util.Primitives;
import java.io.Serializable;
@@ -13,16 +14,37 @@
public class InstanceOf implements ArgumentMatcher<Object>, Serializable {
private final Class<?> clazz;
+ private String description;
public InstanceOf(Class<?> clazz) {
+ this(clazz, "isA(" + clazz.getCanonicalName() + ")");
+ }
+
+ public InstanceOf(Class<?> clazz, String describedAs) {
this.clazz = clazz;
+ this.description = describedAs;
}
public boolean matches(Object actual) {
- return (actual != null) && clazz.isAssignableFrom(actual.getClass());
+ return (actual != null) &&
+ (Primitives.isAssignableFromWrapper(actual.getClass(), clazz)
+ || clazz.isAssignableFrom(actual.getClass()));
}
public String toString() {
- return "isA(" + clazz.getName() + ")";
+ return description;
+ }
+
+ public static class VarArgAware extends InstanceOf implements VarargMatcher {
+
+ public VarArgAware(Class<?> clazz) {
+ super(clazz);
+ }
+
+ public VarArgAware(Class<?> clazz, String describedAs) {
+ super(clazz, describedAs);
+ }
}
+
+
}
diff --git a/src/main/java/org/mockito/internal/util/Primitives.java b/src/main/java/org/mockito/internal/util/Primitives.java
index e7a2f99c24..1540326129 100644
--- a/src/main/java/org/mockito/internal/util/Primitives.java
+++ b/src/main/java/org/mockito/internal/util/Primitives.java
@@ -42,6 +42,13 @@ public static boolean isPrimitiveOrWrapper(Class<?> type) {
return PRIMITIVE_OR_WRAPPER_DEFAULT_VALUES.containsKey(type);
}
+ public static boolean isAssignableFromWrapper(Class<?> valueClass, Class<?> referenceType) {
+ if(isPrimitiveOrWrapper(valueClass) && isPrimitiveOrWrapper(referenceType)) {
+ return Primitives.primitiveTypeOf(valueClass).isAssignableFrom(referenceType);
+ }
+ return false;
+ }
+
/**
* Returns the boxed default value for a primitive or a primitive wrapper.
*
| diff --git a/src/test/java/org/mockito/internal/exceptions/stacktrace/ConditionalStackTraceFilterTest.java b/src/test/java/org/mockito/internal/exceptions/stacktrace/ConditionalStackTraceFilterTest.java
index 64a5a39c52..88e2727b1e 100644
--- a/src/test/java/org/mockito/internal/exceptions/stacktrace/ConditionalStackTraceFilterTest.java
+++ b/src/test/java/org/mockito/internal/exceptions/stacktrace/ConditionalStackTraceFilterTest.java
@@ -4,12 +4,13 @@
*/
package org.mockito.internal.exceptions.stacktrace;
+import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.mockito.exceptions.base.TraceBuilder;
import org.mockito.internal.configuration.ConfigurationAccess;
import org.mockitoutil.TestBase;
-import static org.mockitoutil.ExtraMatchers.hasOnlyThoseClassesInStackTrace;
+import static org.mockitoutil.Conditions.onlyThoseClassesInStackTrace;
public class ConditionalStackTraceFilterTest extends TestBase {
@@ -26,7 +27,7 @@ public void shouldNotFilterWhenConfigurationSaysNo() {
filter.filter(t);
- assertThat(t, hasOnlyThoseClassesInStackTrace("org.mockito.Mockito", "org.test.MockitoSampleTest"));
+ Assertions.assertThat(t).has(onlyThoseClassesInStackTrace("org.mockito.Mockito", "org.test.MockitoSampleTest"));
}
@Test
@@ -40,6 +41,6 @@ public void shouldFilterWhenConfigurationSaysYes() {
filter.filter(t);
- assertThat(t, hasOnlyThoseClassesInStackTrace("org.test.MockitoSampleTest"));
+ Assertions.assertThat(t).has(onlyThoseClassesInStackTrace("org.test.MockitoSampleTest"));
}
}
diff --git a/src/test/java/org/mockito/internal/exceptions/stacktrace/StackTraceFilterTest.java b/src/test/java/org/mockito/internal/exceptions/stacktrace/StackTraceFilterTest.java
index ff33eab770..27ee551479 100644
--- a/src/test/java/org/mockito/internal/exceptions/stacktrace/StackTraceFilterTest.java
+++ b/src/test/java/org/mockito/internal/exceptions/stacktrace/StackTraceFilterTest.java
@@ -5,12 +5,13 @@
package org.mockito.internal.exceptions.stacktrace;
+import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.mockito.exceptions.base.TraceBuilder;
import org.mockitoutil.TestBase;
import static junit.framework.TestCase.assertEquals;
-import static org.mockitoutil.ExtraMatchers.hasOnlyThoseClasses;
+import static org.mockitoutil.Conditions.onlyThoseClasses;
public class StackTraceFilterTest extends TestBase {
@@ -25,7 +26,7 @@ public void shouldFilterOutCglibGarbage() {
StackTraceElement[] filtered = filter.filter(t, false);
- assertThat(filtered, hasOnlyThoseClasses("MockitoExampleTest"));
+ Assertions.assertThat(filtered).has(onlyThoseClasses("MockitoExampleTest"));
}
@Test
@@ -37,7 +38,7 @@ public void shouldFilterOutByteBuddyGarbage() {
StackTraceElement[] filtered = filter.filter(t, false);
- assertThat(filtered, hasOnlyThoseClasses("MockitoExampleTest"));
+ Assertions.assertThat(filtered).has(onlyThoseClasses("MockitoExampleTest"));
}
@@ -49,8 +50,8 @@ public void shouldFilterOutMockitoPackage() {
).toTraceArray();
StackTraceElement[] filtered = filter.filter(t, false);
-
- assertThat(filtered, hasOnlyThoseClasses("org.test.MockitoSampleTest"));
+
+ Assertions.assertThat(filtered).has(onlyThoseClasses("org.test.MockitoSampleTest"));
}
@Test
@@ -64,8 +65,8 @@ public void shouldNotFilterOutTracesMiddleGoodTraces() {
).toTraceArray();
StackTraceElement[] filtered = filter.filter(t, false);
-
- assertThat(filtered, hasOnlyThoseClasses("org.test.TestSupport", "org.test.TestSupport", "org.test.MockitoSampleTest"));
+
+ Assertions.assertThat(filtered).has(onlyThoseClasses("org.test.TestSupport", "org.test.TestSupport", "org.test.MockitoSampleTest"));
}
@Test
@@ -78,8 +79,8 @@ public void shouldKeepRunners() {
).toTraceArray();
StackTraceElement[] filtered = filter.filter(t, false);
-
- assertThat(filtered, hasOnlyThoseClasses("org.test.MockitoSampleTest", "junit.stuff", "org.mockito.runners.Runner"));
+
+ Assertions.assertThat(filtered).has(onlyThoseClasses("org.test.MockitoSampleTest", "junit.stuff", "org.mockito.runners.Runner"));
}
@Test
@@ -95,7 +96,7 @@ public void shouldNotFilterElementsAboveMockitoJUnitRule() {
StackTraceElement[] filtered = filter.filter(t, false);
- assertThat(filtered, hasOnlyThoseClasses("org.test.MockitoSampleTest", "junit.stuff", "org.mockito.runners.Runner","org.mockito.internal.junit.JUnitRule$1.evaluate(JUnitRule.java:16)"));
+ Assertions.assertThat(filtered).has(onlyThoseClasses("org.test.MockitoSampleTest", "junit.stuff", "org.mockito.runners.Runner","org.mockito.internal.junit.JUnitRule$1.evaluate(JUnitRule.java:16)"));
}
@Test
@@ -106,8 +107,8 @@ public void shouldKeepInternalRunners() {
).toTraceArray();
StackTraceElement[] filtered = filter.filter(t, false);
-
- assertThat(filtered, hasOnlyThoseClasses("org.test.MockitoSampleTest", "org.mockito.internal.runners.Runner"));
+
+ Assertions.assertThat(filtered).has(onlyThoseClasses("org.test.MockitoSampleTest", "org.mockito.internal.runners.Runner"));
}
@Test
@@ -123,7 +124,7 @@ public void shouldStartFilteringAndKeepTop() {
StackTraceElement[] filtered = filter.filter(t, true);
//then
- assertThat(filtered, hasOnlyThoseClasses("org.test.MockitoSampleTest", "org.test.Good"));
+ Assertions.assertThat(filtered).has(onlyThoseClasses("org.test.MockitoSampleTest", "org.test.Good"));
}
@Test
@@ -136,8 +137,8 @@ public void shouldKeepGoodTraceFromTheTopBecauseRealImplementationsOfSpiesSometi
).toTraceArray();
StackTraceElement[] filtered = filter.filter(t, true);
-
- assertThat(filtered, hasOnlyThoseClasses(
+
+ Assertions.assertThat(filtered).has(onlyThoseClasses(
"org.test.MockitoSampleTest",
"org.yet.another.good.Trace",
"org.good.Trace"
diff --git a/src/test/java/org/mockito/internal/invocation/InvocationImplTest.java b/src/test/java/org/mockito/internal/invocation/InvocationImplTest.java
index 39d1c32024..5c68e7c536 100644
--- a/src/test/java/org/mockito/internal/invocation/InvocationImplTest.java
+++ b/src/test/java/org/mockito/internal/invocation/InvocationImplTest.java
@@ -5,6 +5,7 @@
package org.mockito.internal.invocation;
+import org.assertj.core.api.Assertions;
import org.junit.Before;
import org.junit.Test;
import org.mockito.exceptions.base.MockitoException;
@@ -69,45 +70,45 @@ public void shouldPrintMethodName() {
@Test
public void shouldPrintMethodArgs() {
invocation = new InvocationBuilder().args("foo").toInvocation();
- assertThat(invocation.toString(), endsWith("simpleMethod(\"foo\");"));
+ Assertions.assertThat(invocation.toString()).endsWith("simpleMethod(\"foo\");");
}
@Test
public void shouldPrintMethodIntegerArgAndString() {
invocation = new InvocationBuilder().args("foo", 1).toInvocation();
- assertThat(invocation.toString(), endsWith("simpleMethod(\"foo\", 1);"));
+ Assertions.assertThat(invocation.toString()).endsWith("simpleMethod(\"foo\", 1);");
}
@Test
public void shouldPrintNull() {
invocation = new InvocationBuilder().args((String) null).toInvocation();
- assertThat(invocation.toString(), endsWith("simpleMethod(null);"));
+ Assertions.assertThat(invocation.toString()).endsWith("simpleMethod(null);");
}
@Test
public void shouldPrintArray() {
invocation = new InvocationBuilder().method("oneArray").args(new int[] { 1, 2, 3 }).toInvocation();
- assertThat(invocation.toString(), endsWith("oneArray([1, 2, 3]);"));
+ Assertions.assertThat(invocation.toString()).endsWith("oneArray([1, 2, 3]);");
}
@Test
public void shouldPrintNullIfArrayIsNull() throws Exception {
Method m = IMethods.class.getMethod("oneArray", Object[].class);
invocation = new InvocationBuilder().method(m).args((Object) null).toInvocation();
- assertThat(invocation.toString(), endsWith("oneArray(null);"));
+ Assertions.assertThat(invocation.toString()).endsWith("oneArray(null);");
}
@Test
public void shouldPrintArgumentsInMultilinesWhenGetsTooBig() {
invocation = new InvocationBuilder().args("veeeeery long string that makes it ugly in one line", 1).toInvocation();
- assertThat(invocation.toString(), endsWith(
+ Assertions.assertThat(invocation.toString()).endsWith(
"simpleMethod(" +
"\n" +
" \"veeeeery long string that makes it ugly in one line\"," +
"\n" +
" 1" +
"\n" +
- ");"));
+ ");");
}
@Test
diff --git a/src/test/java/org/mockito/internal/invocation/InvocationsFinderTest.java b/src/test/java/org/mockito/internal/invocation/InvocationsFinderTest.java
index c34a0258a8..6425ba877b 100644
--- a/src/test/java/org/mockito/internal/invocation/InvocationsFinderTest.java
+++ b/src/test/java/org/mockito/internal/invocation/InvocationsFinderTest.java
@@ -5,6 +5,7 @@
package org.mockito.internal.invocation;
+import org.assertj.core.api.Assertions;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
@@ -20,8 +21,9 @@
import java.util.LinkedList;
import java.util.List;
-import static junit.framework.TestCase.*;
-import static org.mockitoutil.ExtraMatchers.hasExactlyInOrder;
+import static junit.framework.TestCase.assertNull;
+import static junit.framework.TestCase.assertSame;
+import static junit.framework.TestCase.assertTrue;
public class InvocationsFinderTest extends TestBase {
@@ -48,10 +50,10 @@ public void setup() throws Exception {
@Test
public void shouldFindActualInvocations() throws Exception {
List<Invocation> actual = InvocationsFinder.findInvocations(invocations, new InvocationMatcher(simpleMethodInvocation));
- assertThat(actual, hasExactlyInOrder(simpleMethodInvocation, simpleMethodInvocationTwo));
+ Assertions.assertThat(actual).containsSequence(simpleMethodInvocation, simpleMethodInvocationTwo);
actual = InvocationsFinder.findInvocations(invocations, new InvocationMatcher(differentMethodInvocation));
- assertThat(actual, hasExactlyInOrder(differentMethodInvocation));
+ Assertions.assertThat(actual).containsSequence(differentMethodInvocation);
}
@Test
@@ -137,11 +139,11 @@ public void shouldGetLastStackTrace() throws Exception {
@Test
public void shouldFindAllMatchingUnverifiedChunks() throws Exception {
List<Invocation> allMatching = InvocationsFinder.findAllMatchingUnverifiedChunks(invocations, new InvocationMatcher(simpleMethodInvocation), context);
- assertThat(allMatching, hasExactlyInOrder(simpleMethodInvocation, simpleMethodInvocationTwo));
+ Assertions.assertThat(allMatching).containsSequence(simpleMethodInvocation, simpleMethodInvocationTwo);
context.markVerified(simpleMethodInvocation);
allMatching = InvocationsFinder.findAllMatchingUnverifiedChunks(invocations, new InvocationMatcher(simpleMethodInvocation), context);
- assertThat(allMatching, hasExactlyInOrder(simpleMethodInvocationTwo));
+ Assertions.assertThat(allMatching).containsSequence(simpleMethodInvocationTwo);
context.markVerified(simpleMethodInvocationTwo);
allMatching = InvocationsFinder.findAllMatchingUnverifiedChunks(invocations, new InvocationMatcher(simpleMethodInvocation), context);
@@ -151,7 +153,7 @@ public void shouldFindAllMatchingUnverifiedChunks() throws Exception {
@Test
public void shouldFindMatchingChunk() throws Exception {
List<Invocation> chunk = InvocationsFinder.findMatchingChunk(invocations, new InvocationMatcher(simpleMethodInvocation), 2, context);
- assertThat(chunk, hasExactlyInOrder(simpleMethodInvocation, simpleMethodInvocationTwo));
+ Assertions.assertThat(chunk).containsSequence(simpleMethodInvocation, simpleMethodInvocationTwo);
}
@Test
@@ -160,7 +162,7 @@ public void shouldReturnAllChunksWhenModeIsAtLeastOnce() throws Exception {
invocations.add(simpleMethodInvocationThree);
List<Invocation> chunk = InvocationsFinder.findMatchingChunk(invocations, new InvocationMatcher(simpleMethodInvocation), 1, context);
- assertThat(chunk, hasExactlyInOrder(simpleMethodInvocation, simpleMethodInvocationTwo, simpleMethodInvocationThree));
+ Assertions.assertThat(chunk).containsSequence(simpleMethodInvocation, simpleMethodInvocationTwo, simpleMethodInvocationThree);
}
@Test
@@ -169,7 +171,7 @@ public void shouldReturnAllChunksWhenWantedCountDoesntMatch() throws Exception {
invocations.add(simpleMethodInvocationThree);
List<Invocation> chunk = InvocationsFinder.findMatchingChunk(invocations, new InvocationMatcher(simpleMethodInvocation), 1, context);
- assertThat(chunk, hasExactlyInOrder(simpleMethodInvocation, simpleMethodInvocationTwo, simpleMethodInvocationThree));
+ Assertions.assertThat(chunk).containsSequence(simpleMethodInvocation, simpleMethodInvocationTwo, simpleMethodInvocationThree);
}
@Test
diff --git a/src/test/java/org/mockito/internal/matchers/InstanceOfTest.java b/src/test/java/org/mockito/internal/matchers/InstanceOfTest.java
new file mode 100644
index 0000000000..4497c7c60a
--- /dev/null
+++ b/src/test/java/org/mockito/internal/matchers/InstanceOfTest.java
@@ -0,0 +1,64 @@
+package org.mockito.internal.matchers;
+
+import org.junit.Test;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+public class InstanceOfTest {
+
+ @Test
+ public void should_describe_the_matcher() {
+ assertThat(new InstanceOf(Object.class).toString()).contains("isA")
+ .contains("Object");
+ assertThat(new InstanceOf(Object[].class).toString()).contains("isA")
+ .contains("Object[]");
+ assertThat(new InstanceOf(Object.class, "matches something").toString()).isEqualTo("matches something");
+ }
+
+ @Test
+ public void should_check_instance_type() {
+ assertThat(new InstanceOf(Object.class).matches(new Object())).isTrue();
+ assertThat(new InstanceOf(Object.class).matches(new ArrayList())).isTrue();
+ assertThat(new InstanceOf(List.class).matches(new ArrayList())).isTrue();
+ assertThat(new InstanceOf(List.class).matches(new Object())).isFalse();
+ }
+
+ @Test
+ public void should_check_for_primitive_wrapper_types() {
+ assertThat(new InstanceOf(int.class).matches(1000)).isTrue();
+ assertThat(new InstanceOf(Integer.class).matches(1000)).isTrue();
+ assertThat(new InstanceOf(int.class).matches(new Integer(1000))).isTrue();
+ assertThat(new InstanceOf(Integer.class).matches(new Integer(1000))).isTrue();
+
+ assertThat(new InstanceOf(double.class).matches(1000.1)).isTrue();
+ assertThat(new InstanceOf(Double.class).matches(1000.1)).isTrue();
+ assertThat(new InstanceOf(double.class).matches(new Double(1000.1))).isTrue();
+ assertThat(new InstanceOf(Double.class).matches(new Double(1000.1))).isTrue();
+
+ assertThat(new InstanceOf(int.class).matches(1000L)).isFalse();
+ assertThat(new InstanceOf(Integer.class).matches(1000L)).isFalse();
+ assertThat(new InstanceOf(int.class).matches(new Long(1000))).isFalse();
+ assertThat(new InstanceOf(Integer.class).matches(new Long(1000))).isFalse();
+
+ assertThat(new InstanceOf(long.class).matches(1000L)).isTrue();
+ assertThat(new InstanceOf(Long.class).matches(1000L)).isTrue();
+ assertThat(new InstanceOf(long.class).matches(new Long(1000))).isTrue();
+ assertThat(new InstanceOf(Long.class).matches(new Long(1000))).isTrue();
+
+ assertThat(new InstanceOf(long.class).matches(1000)).isFalse();
+ assertThat(new InstanceOf(Long.class).matches(1000)).isFalse();
+ assertThat(new InstanceOf(long.class).matches(new Integer(1000))).isFalse();
+ assertThat(new InstanceOf(Long.class).matches(new Integer(1000))).isFalse();
+ }
+
+ @Test
+ public void can_be_vararg_aware() {
+ assertThat(new InstanceOf.VarArgAware(Number[].class)).isInstanceOf(VarargMatcher.class);
+ assertThat(new InstanceOf.VarArgAware(Number[].class).matches(new Integer[0])).isTrue();
+ assertThat(new InstanceOf.VarArgAware(Number[].class).matches(new Number[0])).isTrue();
+ assertThat(new InstanceOf.VarArgAware(Number[].class).matches(new Object[0])).isFalse();
+ }
+}
\ No newline at end of file
diff --git a/src/test/java/org/mockito/internal/progress/PrimitivesTest.java b/src/test/java/org/mockito/internal/progress/PrimitivesTest.java
deleted file mode 100644
index de24c6a383..0000000000
--- a/src/test/java/org/mockito/internal/progress/PrimitivesTest.java
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * Copyright (c) 2007 Mockito contributors
- * This program is made available under the terms of the MIT License.
- */
-package org.mockito.internal.progress;
-
-import org.junit.Test;
-import org.mockito.internal.util.Primitives;
-
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-
-
-public class PrimitivesTest {
-
-
- @Test
- public void should_not_return_null_for_primitives_wrappers() throws Exception {
- assertNotNull(Primitives.defaultValue(Boolean.class));
- assertNotNull(Primitives.defaultValue(Character.class));
- assertNotNull(Primitives.defaultValue(Byte.class));
- assertNotNull(Primitives.defaultValue(Short.class));
- assertNotNull(Primitives.defaultValue(Integer.class));
- assertNotNull(Primitives.defaultValue(Long.class));
- assertNotNull(Primitives.defaultValue(Float.class));
- assertNotNull(Primitives.defaultValue(Double.class));
- }
-
- @Test
- public void should_not_return_null_for_primitives() throws Exception {
- assertNotNull(Primitives.defaultValue(boolean.class));
- assertNotNull(Primitives.defaultValue(char.class));
- assertNotNull(Primitives.defaultValue(byte.class));
- assertNotNull(Primitives.defaultValue(short.class));
- assertNotNull(Primitives.defaultValue(int.class));
- assertNotNull(Primitives.defaultValue(long.class));
- assertNotNull(Primitives.defaultValue(float.class));
- assertNotNull(Primitives.defaultValue(double.class));
- }
-
- @Test
- public void should_default_values_for_primitive() {
- assertThat(Primitives.defaultValue(boolean.class)).isFalse();
- assertThat(Primitives.defaultValue(char.class)).isEqualTo('\u0000');
- assertThat(Primitives.defaultValue(byte.class)).isEqualTo((byte) 0);
- assertThat(Primitives.defaultValue(short.class)).isEqualTo((short) 0);
- assertThat(Primitives.defaultValue(int.class)).isEqualTo(0);
- assertThat(Primitives.defaultValue(long.class)).isEqualTo(0L);
- assertThat(Primitives.defaultValue(float.class)).isEqualTo(0.0F);
- assertThat(Primitives.defaultValue(double.class)).isEqualTo(0.0D);
- }
-
- @Test
- public void should_default_values_for_wrapper() {
- assertThat(Primitives.defaultValue(Boolean.class)).isFalse();
- assertThat(Primitives.defaultValue(Character.class)).isEqualTo('\u0000');
- assertThat(Primitives.defaultValue(Byte.class)).isEqualTo((byte) 0);
- assertThat(Primitives.defaultValue(Short.class)).isEqualTo((short) 0);
- assertThat(Primitives.defaultValue(Integer.class)).isEqualTo(0);
- assertThat(Primitives.defaultValue(Long.class)).isEqualTo(0L);
- assertThat(Primitives.defaultValue(Float.class)).isEqualTo(0.0F);
- assertThat(Primitives.defaultValue(Double.class)).isEqualTo(0.0D);
- }
-
- @Test
- public void should_return_null_for_everything_else() throws Exception {
- assertNull(Primitives.defaultValue(Object.class));
- assertNull(Primitives.defaultValue(String.class));
- assertNull(Primitives.defaultValue(null));
- }
-}
\ No newline at end of file
diff --git a/src/test/java/org/mockito/internal/util/PrimitivesTest.java b/src/test/java/org/mockito/internal/util/PrimitivesTest.java
index 839763f820..2ea86c6118 100644
--- a/src/test/java/org/mockito/internal/util/PrimitivesTest.java
+++ b/src/test/java/org/mockito/internal/util/PrimitivesTest.java
@@ -12,8 +12,6 @@
public class PrimitivesTest {
-
-
@Test
public void should_not_return_null_for_primitives_wrappers() throws Exception {
assertNotNull(Primitives.defaultValue(Boolean.class));
@@ -68,4 +66,24 @@ public void should_return_null_for_everything_else() throws Exception {
assertNull(Primitives.defaultValue(String.class));
assertNull(Primitives.defaultValue(null));
}
+
+ @Test
+ public void should_check_that_value_type_is_assignable_to_wrapper_reference() {
+ assertThat(Primitives.isAssignableFromWrapper(int.class, Integer.class));
+ assertThat(Primitives.isAssignableFromWrapper(Integer.class, Integer.class));
+ assertThat(Primitives.isAssignableFromWrapper(long.class, Long.class));
+ assertThat(Primitives.isAssignableFromWrapper(Long.class, Long.class));
+ assertThat(Primitives.isAssignableFromWrapper(double.class, Double.class));
+ assertThat(Primitives.isAssignableFromWrapper(Double.class, Double.class));
+ assertThat(Primitives.isAssignableFromWrapper(float.class, Float.class));
+ assertThat(Primitives.isAssignableFromWrapper(Float.class, Float.class));
+ assertThat(Primitives.isAssignableFromWrapper(char.class, Character.class));
+ assertThat(Primitives.isAssignableFromWrapper(Character.class, Character.class));
+ assertThat(Primitives.isAssignableFromWrapper(short.class, Short.class));
+ assertThat(Primitives.isAssignableFromWrapper(Short.class, Short.class));
+ assertThat(Primitives.isAssignableFromWrapper(byte.class, Byte.class));
+ assertThat(Primitives.isAssignableFromWrapper(Byte.class, Byte.class));
+ assertThat(Primitives.isAssignableFromWrapper(boolean.class, Boolean.class));
+ assertThat(Primitives.isAssignableFromWrapper(Boolean.class, Boolean.class));
+ }
}
\ No newline at end of file
diff --git a/src/test/java/org/mockito/internal/util/TimerTest.java b/src/test/java/org/mockito/internal/util/TimerTest.java
index e1156688c1..49cd3c7cae 100644
--- a/src/test/java/org/mockito/internal/util/TimerTest.java
+++ b/src/test/java/org/mockito/internal/util/TimerTest.java
@@ -1,12 +1,11 @@
package org.mockito.internal.util;
+import org.assertj.core.api.Assertions;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.exceptions.misusing.FriendlyReminderException;
import org.mockitoutil.TestBase;
-import static org.hamcrest.CoreMatchers.is;
-
public class TimerTest extends TestBase {
@Test
@@ -19,7 +18,7 @@ public void should_return_true_if_task_is_in_acceptable_time_bounds() {
timer.start();
//then
- assertThat(timer.isCounting(), is(true));
+ Assertions.assertThat(timer.isCounting()).isTrue();
}
@Test
@@ -32,7 +31,7 @@ public void should_return_false_when_time_run_out() throws Exception {
oneMillisecondPasses();
//then
- assertThat(timer.isCounting(), is(false));
+ Assertions.assertThat(timer.isCounting()).isFalse();
}
@Test
diff --git a/src/test/java/org/mockito/internal/util/collections/ListUtilTest.java b/src/test/java/org/mockito/internal/util/collections/ListUtilTest.java
index 594fbc3d25..fcd4f9704a 100644
--- a/src/test/java/org/mockito/internal/util/collections/ListUtilTest.java
+++ b/src/test/java/org/mockito/internal/util/collections/ListUtilTest.java
@@ -5,6 +5,7 @@
package org.mockito.internal.util.collections;
+import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.mockito.internal.util.collections.ListUtil.Filter;
import org.mockitoutil.TestBase;
@@ -14,7 +15,6 @@
import static java.util.Arrays.asList;
import static junit.framework.TestCase.assertTrue;
-import static org.mockitoutil.ExtraMatchers.hasExactlyInOrder;
public class ListUtilTest extends TestBase {
@@ -26,8 +26,8 @@ public boolean isOut(String object) {
return object == "x";
}
});
-
- assertThat(filtered, hasExactlyInOrder("one", "two", "three"));
+
+ Assertions.assertThat(filtered).containsSequence("one", "two", "three");
}
@Test
diff --git a/src/test/java/org/mockitousage/IMethods.java b/src/test/java/org/mockitousage/IMethods.java
index a18d04697d..7234bd7976 100644
--- a/src/test/java/org/mockitousage/IMethods.java
+++ b/src/test/java/org/mockitousage/IMethods.java
@@ -190,6 +190,8 @@ public interface IMethods {
String forCollection(Collection<String> collection);
+ String forIterable(Iterable<String> iterable);
+
Object[] arrayReturningMethod();
IMethods iMethodsReturningMethod();
@@ -202,6 +204,8 @@ public interface IMethods {
Object collectionArgMethod(Collection<String> collection);
+ Object iterableArgMethod(Iterable<String> collection);
+
Object setArgMethod(Set<String> set);
void longArg(long longArg);
diff --git a/src/test/java/org/mockitousage/MethodsImpl.java b/src/test/java/org/mockitousage/MethodsImpl.java
index cc4fb4155d..4f4bdcc8d8 100644
--- a/src/test/java/org/mockitousage/MethodsImpl.java
+++ b/src/test/java/org/mockitousage/MethodsImpl.java
@@ -363,6 +363,10 @@ public String forCollection(Collection<String> collection) {
return null;
}
+ public String forIterable(Iterable<String> iterable) {
+ return null;
+ }
+
public Object[] arrayReturningMethod() {
return new Object[0];
}
@@ -387,6 +391,10 @@ public Object collectionArgMethod(Collection<String> collection) {
return null;
}
+ public Object iterableArgMethod(Iterable<String> iterable) {
+ return null;
+ }
+
public Object setArgMethod(Set<String> set) {
return null;
}
diff --git a/src/test/java/org/mockitousage/basicapi/ReplacingObjectMethodsTest.java b/src/test/java/org/mockitousage/basicapi/ReplacingObjectMethodsTest.java
index bc79a68e5e..dc6258c297 100644
--- a/src/test/java/org/mockitousage/basicapi/ReplacingObjectMethodsTest.java
+++ b/src/test/java/org/mockitousage/basicapi/ReplacingObjectMethodsTest.java
@@ -5,13 +5,12 @@
package org.mockitousage.basicapi;
+import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.mockito.Mockito;
import org.mockitoutil.TestBase;
import static junit.framework.TestCase.assertEquals;
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.not;
public class ReplacingObjectMethodsTest extends TestBase {
@@ -30,12 +29,11 @@ public void shouldProvideMockyImplementationOfToString() {
public void shouldReplaceObjectMethods() {
Object mock = Mockito.mock(ObjectMethodsOverridden.class);
Object otherMock = Mockito.mock(ObjectMethodsOverridden.class);
-
- assertThat(mock, equalTo(mock));
- assertThat(mock, not(equalTo(otherMock)));
-
- assertThat(mock.hashCode(), not(equalTo(otherMock.hashCode())));
-
+
+ Assertions.assertThat(mock).isEqualTo(mock);
+ Assertions.assertThat(mock).isNotEqualTo(otherMock);
+ Assertions.assertThat(mock.hashCode()).isNotEqualTo(otherMock.hashCode());
+
assertContains("Mock for ObjectMethodsOverridden", mock.toString());
}
@@ -43,12 +41,11 @@ public void shouldReplaceObjectMethods() {
public void shouldReplaceObjectMethodsWhenOverridden() {
Object mock = Mockito.mock(ObjectMethodsOverriddenSubclass.class);
Object otherMock = Mockito.mock(ObjectMethodsOverriddenSubclass.class);
-
- assertThat(mock, equalTo(mock));
- assertThat(mock, not(equalTo(otherMock)));
-
- assertThat(mock.hashCode(), not(equalTo(otherMock.hashCode())));
-
+
+ Assertions.assertThat(mock).isEqualTo(mock);
+ Assertions.assertThat(mock).isNotEqualTo(otherMock);
+ Assertions.assertThat(mock.hashCode()).isNotEqualTo(otherMock.hashCode());
+
assertContains("Mock for ObjectMethodsOverriddenSubclass", mock.toString());
}
diff --git a/src/test/java/org/mockitousage/internal/invocation/realmethod/CleanTraceRealMethodTest.java b/src/test/java/org/mockitousage/internal/invocation/realmethod/CleanTraceRealMethodTest.java
index 48ee1e31be..10ec3da6b5 100644
--- a/src/test/java/org/mockitousage/internal/invocation/realmethod/CleanTraceRealMethodTest.java
+++ b/src/test/java/org/mockitousage/internal/invocation/realmethod/CleanTraceRealMethodTest.java
@@ -4,6 +4,7 @@
*/
package org.mockitousage.internal.invocation.realmethod;
+import org.assertj.core.api.Assertions;
import org.junit.Before;
import org.junit.Test;
import org.mockito.internal.invocation.realmethod.CleanTraceRealMethod;
@@ -11,7 +12,7 @@
import org.mockitoutil.TestBase;
import static junit.framework.TestCase.fail;
-import static org.mockitoutil.ExtraMatchers.hasMethodInStackTraceAt;
+import static org.mockitoutil.Conditions.methodInStackTraceAt;
public class CleanTraceRealMethodTest extends TestBase {
@@ -42,9 +43,9 @@ public Object invoke(Object target, Object[] arguments) throws Throwable {
fail();
//then
} catch (Exception e) {
- assertThat(e, hasMethodInStackTraceAt(0, "throwSomething"));
- assertThat(e, hasMethodInStackTraceAt(1, "invoke"));
- assertThat(e, hasMethodInStackTraceAt(2, "shouldRemoveMockitoInternalsFromStackTraceWhenRealMethodThrows"));
+ Assertions.assertThat(e).has(methodInStackTraceAt(0, "throwSomething"));
+ Assertions.assertThat(e).has(methodInStackTraceAt(1, "invoke"));
+ Assertions.assertThat(e).has(methodInStackTraceAt(2, "shouldRemoveMockitoInternalsFromStackTraceWhenRealMethodThrows"));
}
}
}
\ No newline at end of file
diff --git a/src/test/java/org/mockitousage/junitrunner/SilentRunnerTest.java b/src/test/java/org/mockitousage/junitrunner/SilentRunnerTest.java
index 134bea8944..df90dc10d2 100644
--- a/src/test/java/org/mockitousage/junitrunner/SilentRunnerTest.java
+++ b/src/test/java/org/mockitousage/junitrunner/SilentRunnerTest.java
@@ -9,12 +9,16 @@
import org.mockito.exceptions.verification.TooLittleActualInvocations;
import org.mockito.runners.MockitoJUnitRunner;
import org.mockitousage.IMethods;
+import org.mockitoutil.JUnitResultAssert;
import org.mockitoutil.TestBase;
import java.util.List;
import static org.junit.Assert.assertEquals;
-import static org.mockito.Mockito.*;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
/**
* Created by sfaber on 4/22/16.
@@ -29,7 +33,7 @@ public class SilentRunnerTest extends TestBase {
SomeFeature.class
);
//then
- assertThat(result).isSuccessful();
+ JUnitResultAssert.assertThat(result).isSuccessful();
}
@Test public void failing_test() {
@@ -38,7 +42,7 @@ public class SilentRunnerTest extends TestBase {
SomeFailingFeature.class
);
//then
- assertThat(result).fails(1, TooLittleActualInvocations.class);
+ JUnitResultAssert.assertThat(result).fails(1, TooLittleActualInvocations.class);
}
@Test public void validates_framework_usage() {
@@ -47,7 +51,7 @@ public class SilentRunnerTest extends TestBase {
UsesFrameworkIncorrectly.class
);
//then
- assertThat(result).fails(1, UnfinishedStubbingException.class);
+ JUnitResultAssert.assertThat(result).fails(1, UnfinishedStubbingException.class);
}
@Test
@@ -56,7 +60,7 @@ public void ignores_unused_stubs() {
//when
Result result = runner.run(HasUnnecessaryStubs.class);
//then
- assertThat(result).isSuccessful();
+ JUnitResultAssert.assertThat(result).isSuccessful();
}
@RunWith(MockitoJUnitRunner.Silent.class)
diff --git a/src/test/java/org/mockitousage/junitrunner/StrictRunnerTest.java b/src/test/java/org/mockitousage/junitrunner/StrictRunnerTest.java
index bcd298edb1..c12df6acbf 100644
--- a/src/test/java/org/mockitousage/junitrunner/StrictRunnerTest.java
+++ b/src/test/java/org/mockitousage/junitrunner/StrictRunnerTest.java
@@ -9,12 +9,14 @@
import org.mockito.exceptions.misusing.UnnecessaryStubbingException;
import org.mockito.runners.MockitoJUnitRunner;
import org.mockitousage.IMethods;
+import org.mockitoutil.JUnitResultAssert;
import org.mockitoutil.TestBase;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
+
/**
* Created by sfaber on 4/22/16.
*/
@@ -30,7 +32,7 @@ public class StrictRunnerTest extends TestBase {
StubbingInTestUsed.class
);
//then
- assertThat(result).isSuccessful();
+ JUnitResultAssert.assertThat(result).isSuccessful();
}
@Test public void fails_when_stubs_were_not_used() {
@@ -42,7 +44,7 @@ public class StrictRunnerTest extends TestBase {
Result result = runner.run(tests);
//then
- assertThat(result).fails(3, UnnecessaryStubbingException.class);
+ JUnitResultAssert.assertThat(result).fails(3, UnnecessaryStubbingException.class);
}
@Test public void does_not_report_unused_stubs_when_different_failure_is_present() {
@@ -50,7 +52,7 @@ public class StrictRunnerTest extends TestBase {
Result result = runner.run(WithUnrelatedAssertionFailure.class);
//then
- assertThat(result).fails(1, MyAssertionError.class);
+ JUnitResultAssert.assertThat(result).fails(1, MyAssertionError.class);
}
@RunWith(MockitoJUnitRunner.class)
diff --git a/src/test/java/org/mockitousage/matchers/MatchersTest.java b/src/test/java/org/mockitousage/matchers/MatchersTest.java
index 86f476cc84..46b0caeb52 100644
--- a/src/test/java/org/mockitousage/matchers/MatchersTest.java
+++ b/src/test/java/org/mockitousage/matchers/MatchersTest.java
@@ -436,6 +436,27 @@ public void nullMatcher() {
assertEquals("2", mock.threeArgumentMethod(1, new Object(), ""));
}
+ @Test
+ public void nullMatcherForPrimitiveWrappers() {
+ when(mock.forBoolean(isNull(Boolean.class))).thenReturn("ok");
+ when(mock.forInteger(isNull(Integer.class))).thenReturn("ok");
+ when(mock.forLong(isNull(Long.class))).thenReturn("ok");
+ when(mock.forByte(isNull(Byte.class))).thenReturn("ok");
+ when(mock.forShort(isNull(Short.class))).thenReturn("ok");
+ when(mock.forCharacter(isNull(Character.class))).thenReturn("ok");
+ when(mock.forDouble(isNull(Double.class))).thenReturn("ok");
+ when(mock.forFloat(isNull(Float.class))).thenReturn("ok");
+
+ assertEquals("ok", mock.forBoolean(null));
+ assertEquals("ok", mock.forInteger(null));
+ assertEquals("ok", mock.forLong(null));
+ assertEquals("ok", mock.forByte(null));
+ assertEquals("ok", mock.forShort(null));
+ assertEquals("ok", mock.forCharacter(null));
+ assertEquals("ok", mock.forDouble(null));
+ assertEquals("ok", mock.forFloat(null));
+ }
+
@Test
public void notNullMatcher() {
when(mock.threeArgumentMethod(eq(1), notNull(), eq(""))).thenReturn("1");
diff --git a/src/test/java/org/mockitousage/matchers/MoreMatchersTest.java b/src/test/java/org/mockitousage/matchers/MoreMatchersTest.java
index 026905bae6..3471fe0a19 100644
--- a/src/test/java/org/mockitousage/matchers/MoreMatchersTest.java
+++ b/src/test/java/org/mockitousage/matchers/MoreMatchersTest.java
@@ -13,6 +13,7 @@
import java.util.*;
import static junit.framework.TestCase.assertEquals;
+import static junit.framework.TestCase.fail;
import static org.mockito.Matchers.*;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -22,22 +23,41 @@ public class MoreMatchersTest extends TestBase {
@Mock private IMethods mock;
@Test
- public void shouldHelpOutWithUnnecessaryCasting() {
+ public void should_help_out_with_unnecessary_casting() {
when(mock.objectArgMethod(any(String.class))).thenReturn("string");
assertEquals("string", mock.objectArgMethod("foo"));
}
@Test
- public void shouldAnyBeActualAliasToAnyObject() {
+ public void any_should_be_actual_alias_to_anyObject() {
mock.simpleMethod((Object) null);
+ verify(mock).simpleMethod(any());
verify(mock).simpleMethod(anyObject());
- verify(mock).simpleMethod(any(Object.class));
}
@Test
- public void shouldHelpOutWithUnnecessaryCastingOfLists() {
+ public void any_class_should_be_actual_alias_to_isA() {
+ mock.simpleMethod(new ArrayList());
+
+ verify(mock).simpleMethod(isA(List.class));
+ verify(mock).simpleMethod(any(List.class));
+
+
+ mock.simpleMethod((String) null);
+ try {
+ verify(mock).simpleMethod(isA(String.class));
+ fail();
+ } catch (AssertionError ignored) { }
+ try {
+ verify(mock).simpleMethod(any(String.class));
+ fail();
+ } catch (AssertionError ignored) { }
+ }
+
+ @Test
+ public void should_help_out_with_unnecessary_casting_of_lists() {
//Below yields compiler warning:
//when(mock.listArgMethod(anyList())).thenReturn("list");
when(mock.listArgMethod(anyListOf(String.class))).thenReturn("list");
@@ -47,7 +67,7 @@ public void shouldHelpOutWithUnnecessaryCastingOfLists() {
}
@Test
- public void shouldHelpOutWithUnnecessaryCastingOfSets() {
+ public void should_help_out_with_unnecessary_casting_of_sets() {
//Below yields compiler warning:
//when(mock.setArgMethod(anySet())).thenReturn("set");
when(mock.setArgMethod(anySetOf(String.class))).thenReturn("set");
@@ -57,7 +77,7 @@ public void shouldHelpOutWithUnnecessaryCastingOfSets() {
}
@Test
- public void shouldHelpOutWithUnnecessaryCastingOfMaps() {
+ public void should_help_out_with_unnecessary_casting_of_maps() {
//Below yields compiler warning:
//when(mock.setArgMethod(anySet())).thenReturn("set");
when(mock.forMap(anyMapOf(String.class, String.class))).thenReturn("map");
@@ -67,17 +87,27 @@ public void shouldHelpOutWithUnnecessaryCastingOfMaps() {
}
@Test
- public void shouldHelpOutWithUnnecessaryCastingOfCollections() {
+ public void should_help_out_with_unnecessary_casting_of_collections() {
+ //Below yields compiler warning:
+ //when(mock.setArgMethod(anySet())).thenReturn("set");
+ when(mock.collectionArgMethod(anyCollectionOf(String.class))).thenReturn("collection");
+
+ assertEquals("collection", mock.collectionArgMethod(new ArrayList<String>()));
+ assertEquals("collection", mock.collectionArgMethod(Collections.<String>emptyList()));
+ }
+
+ @Test
+ public void should_help_out_with_unnecessary_casting_of_iterables() {
//Below yields compiler warning:
//when(mock.setArgMethod(anySet())).thenReturn("set");
- when(mock.collectionArgMethod(anyCollectionOf(String.class))).thenReturn("col");
+ when(mock.iterableArgMethod(anyIterableOf(String.class))).thenReturn("iterable");
- assertEquals("col", mock.collectionArgMethod(new ArrayList<String>()));
- assertEquals("col", mock.collectionArgMethod(Collections.<String>emptyList()));
+ assertEquals("iterable", mock.iterableArgMethod(new ArrayList<String>()));
+ assertEquals("iterable", mock.iterableArgMethod(Collections.<String>emptyList()));
}
@Test
- public void shouldHelpOutWithUnnecessaryCastingOfNullityChecks() {
+ public void should_help_out_with_unnecessary_casting_of_nullity_checks() {
when(mock.objectArgMethod(isNull(LinkedList.class))).thenReturn("string");
when(mock.objectArgMethod(notNull(LinkedList.class))).thenReturn("string");
when(mock.objectArgMethod(isNotNull(LinkedList.class))).thenReturn("string");
diff --git a/src/test/java/org/mockitousage/matchers/NewMatchersTest.java b/src/test/java/org/mockitousage/matchers/NewMatchersTest.java
index 89b31cf02d..7c1dcffe0b 100644
--- a/src/test/java/org/mockitousage/matchers/NewMatchersTest.java
+++ b/src/test/java/org/mockitousage/matchers/NewMatchersTest.java
@@ -70,4 +70,14 @@ public void shouldAllowAnySet() {
verify(mock, times(1)).forSet(anySet());
}
+
+ @Test
+ public void shouldAllowAnyIterable() {
+ when(mock.forIterable(anyIterable())).thenReturn("matched");
+
+ assertEquals("matched", mock.forIterable(new HashSet<String>()));
+ assertEquals(null, mock.forIterable(null));
+
+ verify(mock, times(1)).forIterable(anyIterable());
+ }
}
\ No newline at end of file
diff --git a/src/test/java/org/mockitousage/puzzlers/BridgeMethodPuzzleTest.java b/src/test/java/org/mockitousage/puzzlers/BridgeMethodPuzzleTest.java
index 89a98fd664..a4c2061058 100644
--- a/src/test/java/org/mockitousage/puzzlers/BridgeMethodPuzzleTest.java
+++ b/src/test/java/org/mockitousage/puzzlers/BridgeMethodPuzzleTest.java
@@ -5,13 +5,14 @@
package org.mockitousage.puzzlers;
+import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.mockitoutil.TestBase;
import static junit.framework.TestCase.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
-import static org.mockitoutil.ExtraMatchers.hasBridgeMethod;
+import static org.mockitoutil.Conditions.bridgeMethod;
/**
* Bridge method is generated by compiler when erasure in parent class is
@@ -42,8 +43,8 @@ public void shouldHaveBridgeMethod() throws Exception {
assertEquals("Dummy says: Hello", s.say("Hello"));
- assertThat(Sub.class, hasBridgeMethod("say"));
- assertThat(s, hasBridgeMethod("say"));
+ Assertions.assertThat(Sub.class).has(bridgeMethod("say"));
+ Assertions.assertThat(s).has(bridgeMethod("say"));
}
@Test
diff --git a/src/test/java/org/mockitousage/spies/PartialMockingWithSpiesTest.java b/src/test/java/org/mockitousage/spies/PartialMockingWithSpiesTest.java
index a863f3a368..d70dc14cc5 100644
--- a/src/test/java/org/mockitousage/spies/PartialMockingWithSpiesTest.java
+++ b/src/test/java/org/mockitousage/spies/PartialMockingWithSpiesTest.java
@@ -5,14 +5,18 @@
package org.mockitousage.spies;
+import org.assertj.core.api.Assertions;
import org.junit.Before;
import org.junit.Test;
-import org.mockitoutil.ExtraMatchers;
import org.mockitoutil.TestBase;
import static junit.framework.TestCase.assertEquals;
import static junit.framework.TestCase.fail;
-import static org.mockito.Mockito.*;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static org.mockitoutil.Conditions.methodsInStackTrace;
@SuppressWarnings("unchecked")
public class PartialMockingWithSpiesTest extends TestBase {
@@ -105,7 +109,7 @@ public void shouldStackTraceGetFilteredOnUserExceptions() {
fail();
} catch (Throwable t) {
// then
- assertThat(t, ExtraMatchers.hasMethodsInStackTrace(
+ Assertions.assertThat(t).has(methodsInStackTrace(
"throwSomeException",
"getNameButDelegateToMethodThatThrows",
"shouldStackTraceGetFilteredOnUserExceptions"
diff --git a/src/test/java/org/mockitousage/spies/SpyingOnInterfacesTest.java b/src/test/java/org/mockitousage/spies/SpyingOnInterfacesTest.java
index 056603db94..22d6b26c77 100644
--- a/src/test/java/org/mockitousage/spies/SpyingOnInterfacesTest.java
+++ b/src/test/java/org/mockitousage/spies/SpyingOnInterfacesTest.java
@@ -11,6 +11,7 @@
import net.bytebuddy.description.modifier.Visibility;
import net.bytebuddy.dynamic.loading.ClassLoadingStrategy;
import net.bytebuddy.implementation.FixedValue;
+import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.mockito.exceptions.base.MockitoException;
import org.mockito.invocation.InvocationOnMock;
@@ -20,9 +21,11 @@
import java.util.List;
import static junit.framework.TestCase.fail;
-import static org.hamcrest.core.Is.is;
import static org.junit.Assume.assumeTrue;
-import static org.mockito.Mockito.*;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
@SuppressWarnings({"unchecked"})
public class SpyingOnInterfacesTest extends TestBase {
@@ -77,7 +80,7 @@ public void shouldAllowDelegatingToDefaultMethod() throws Exception {
//when
when(type.getMethod("foo").invoke(object)).thenCallRealMethod();
//then
- assertThat(type.getMethod("foo").invoke(object), is((Object) "bar"));
+ Assertions.assertThat(type.getMethod("foo").invoke(object)).isEqualTo((Object) "bar");
type.getMethod("foo").invoke(verify(object));
}
@@ -103,7 +106,7 @@ public void shouldAllowSpyingOnDefaultMethod() throws Exception {
Object object = spy(impl.newInstance());
//when
- assertThat(impl.getMethod("foo").invoke(object), is((Object) "bar"));
+ Assertions.assertThat(impl.getMethod("foo").invoke(object)).isEqualTo((Object) "bar");
//then
impl.getMethod("foo").invoke(verify(object));
}
diff --git a/src/test/java/org/mockitousage/stacktrace/StackTraceFilteringTest.java b/src/test/java/org/mockitousage/stacktrace/StackTraceFilteringTest.java
index ee2cd2da85..7c925c0073 100644
--- a/src/test/java/org/mockitousage/stacktrace/StackTraceFilteringTest.java
+++ b/src/test/java/org/mockitousage/stacktrace/StackTraceFilteringTest.java
@@ -5,6 +5,7 @@
package org.mockitousage.stacktrace;
+import org.assertj.core.api.Assertions;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@@ -18,8 +19,12 @@
import org.mockitoutil.TestBase;
import static junit.framework.TestCase.fail;
-import static org.mockito.Mockito.*;
-import static org.mockitoutil.ExtraMatchers.hasFirstMethodInStackTrace;
+import static org.mockito.Mockito.inOrder;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoMoreInteractions;
+import static org.mockito.Mockito.verifyZeroInteractions;
+import static org.mockito.Mockito.when;
+import static org.mockitoutil.Conditions.firstMethodInStackTrace;
public class StackTraceFilteringTest extends TestBase {
@@ -41,7 +46,7 @@ public void shouldFilterStackTraceOnVerify() {
verify(mock).simpleMethod();
fail();
} catch (WantedButNotInvoked e) {
- assertThat(e, hasFirstMethodInStackTrace("shouldFilterStackTraceOnVerify"));
+ Assertions.assertThat(e).has(firstMethodInStackTrace("shouldFilterStackTraceOnVerify"));
}
}
@@ -52,7 +57,7 @@ public void shouldFilterStackTraceOnVerifyNoMoreInteractions() {
verifyNoMoreInteractions(mock);
fail();
} catch (NoInteractionsWanted e) {
- assertThat(e, hasFirstMethodInStackTrace("shouldFilterStackTraceOnVerifyNoMoreInteractions"));
+ Assertions.assertThat(e).has(firstMethodInStackTrace("shouldFilterStackTraceOnVerifyNoMoreInteractions"));
}
}
@@ -63,7 +68,7 @@ public void shouldFilterStackTraceOnVerifyZeroInteractions() {
verifyZeroInteractions(mock);
fail();
} catch (NoInteractionsWanted e) {
- assertThat(e, hasFirstMethodInStackTrace("shouldFilterStackTraceOnVerifyZeroInteractions"));
+ Assertions.assertThat(e).has(firstMethodInStackTrace("shouldFilterStackTraceOnVerifyZeroInteractions"));
}
}
@@ -74,7 +79,7 @@ public void shouldFilterStacktraceOnMockitoException() {
verify(mock).oneArg(true);
fail();
} catch (MockitoException expected) {
- assertThat(expected, hasFirstMethodInStackTrace("shouldFilterStacktraceOnMockitoException"));
+ Assertions.assertThat(expected).has(firstMethodInStackTrace("shouldFilterStacktraceOnMockitoException"));
}
}
@@ -89,7 +94,7 @@ public void shouldFilterStacktraceWhenVerifyingInOrder() {
inOrder.verify(mock).oneArg(true);
fail();
} catch (VerificationInOrderFailure e) {
- assertThat(e, hasFirstMethodInStackTrace("shouldFilterStacktraceWhenVerifyingInOrder"));
+ Assertions.assertThat(e).has(firstMethodInStackTrace("shouldFilterStacktraceWhenVerifyingInOrder"));
}
}
@@ -99,7 +104,7 @@ public void shouldFilterStacktraceWhenInOrderThrowsMockitoException() {
inOrder();
fail();
} catch (MockitoException expected) {
- assertThat(expected, hasFirstMethodInStackTrace("shouldFilterStacktraceWhenInOrderThrowsMockitoException"));
+ Assertions.assertThat(expected).has(firstMethodInStackTrace("shouldFilterStacktraceWhenInOrderThrowsMockitoException"));
}
}
@@ -110,7 +115,7 @@ public void shouldFilterStacktraceWhenInOrderVerifies() {
inOrder.verify(null);
fail();
} catch (MockitoException expected) {
- assertThat(expected, hasFirstMethodInStackTrace("shouldFilterStacktraceWhenInOrderVerifies"));
+ Assertions.assertThat(expected).has(firstMethodInStackTrace("shouldFilterStacktraceWhenInOrderVerifies"));
}
}
@@ -120,7 +125,7 @@ public void shouldFilterStackTraceWhenThrowingExceptionFromMockHandler() {
when(mock.oneArg(true)).thenThrow(new Exception());
fail();
} catch (MockitoException expected) {
- assertThat(expected, hasFirstMethodInStackTrace("shouldFilterStackTraceWhenThrowingExceptionFromMockHandler"));
+ Assertions.assertThat(expected).has(firstMethodInStackTrace("shouldFilterStackTraceWhenThrowingExceptionFromMockHandler"));
}
}
@@ -132,7 +137,7 @@ public void shouldShowProperExceptionStackTrace() throws Exception {
mock.simpleMethod();
fail();
} catch (RuntimeException e) {
- assertThat(e, hasFirstMethodInStackTrace("shouldShowProperExceptionStackTrace"));
+ Assertions.assertThat(e).has(firstMethodInStackTrace("shouldShowProperExceptionStackTrace"));
}
}
}
diff --git a/src/test/java/org/mockitousage/verification/DescriptiveMessagesWhenVerificationFailsTest.java b/src/test/java/org/mockitousage/verification/DescriptiveMessagesWhenVerificationFailsTest.java
index 4a3a7ba7a2..d8e5bd157b 100644
--- a/src/test/java/org/mockitousage/verification/DescriptiveMessagesWhenVerificationFailsTest.java
+++ b/src/test/java/org/mockitousage/verification/DescriptiveMessagesWhenVerificationFailsTest.java
@@ -237,7 +237,7 @@ public void should_print_method_when_matcher_used() throws Exception {
"Wanted but not invoked:" +
"\n" +
"iMethods.twoArgumentMethod(\n" +
- " isA(java.lang.Integer),\n" +
+ " <any integer>,\n" +
" 100\n" +
");";
assertContains(expectedMessage, actualMessage);
diff --git a/src/test/java/org/mockitousage/verification/PrintingVerboseTypesWithArgumentsTest.java b/src/test/java/org/mockitousage/verification/PrintingVerboseTypesWithArgumentsTest.java
index 5e6c8624f5..4149e8b5bc 100644
--- a/src/test/java/org/mockitousage/verification/PrintingVerboseTypesWithArgumentsTest.java
+++ b/src/test/java/org/mockitousage/verification/PrintingVerboseTypesWithArgumentsTest.java
@@ -5,13 +5,14 @@
package org.mockitousage.verification;
+import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.mockito.exceptions.verification.junit.ArgumentsAreDifferent;
import org.mockitousage.IMethods;
import org.mockitoutil.TestBase;
import static junit.framework.TestCase.fail;
-import static org.mockito.Matchers.any;
+import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
@@ -21,17 +22,17 @@ public class PrintingVerboseTypesWithArgumentsTest extends TestBase {
class Boo {
public void withLong(long x) {
}
-
+
public void withLongAndInt(long x, int y) {
}
}
-
+
@Test
- public void shouldNotReportArgumentTypesWhenToStringIsTheSame() throws Exception {
+ public void should_not_report_argument_types_when_to_string_is_the_same() {
//given
Boo boo = mock(Boo.class);
boo.withLong(100);
-
+
try {
//when
verify(boo).withLong(eq(100));
@@ -42,13 +43,13 @@ public void shouldNotReportArgumentTypesWhenToStringIsTheSame() throws Exception
assertContains("withLong((Long) 100);", e.getMessage());
}
}
-
+
@Test
- public void shouldShowTheTypeOfOnlyTheArgumentThatDoesntMatch() throws Exception {
+ public void should_show_the_type_of_only_the_argument_that_doesnt_match() {
//given
Boo boo = mock(Boo.class);
boo.withLongAndInt(100, 200);
-
+
try {
//when
verify(boo).withLongAndInt(eq(100), eq(200));
@@ -59,30 +60,37 @@ public void shouldShowTheTypeOfOnlyTheArgumentThatDoesntMatch() throws Exception
assertContains("withLongAndInt((Long) 100, 200)", e.getMessage());
}
}
-
+
@Test
- public void shouldShowTheTypeOfTheMismatchingArgumentWhenOutputDescriptionsForInvocationsAreDifferent() throws Exception {
+ public void should_show_the_type_of_the_mismatching_argument_when_output_descriptions_for_invocations_are_different() {
//given
Boo boo = mock(Boo.class);
boo.withLongAndInt(100, 200);
-
+
try {
//when
verify(boo).withLongAndInt(eq(100), any(Integer.class));
fail();
} catch (ArgumentsAreDifferent e) {
//then
- assertContains("withLongAndInt((Long) 100, 200)", e.getMessage());
- assertContains("withLongAndInt((Integer) 100, <any>", e.getMessage());
+ Assertions.assertThat(e.getMessage())
+ .contains("withLongAndInt(\n" +
+ " (Long) 100,\n" +
+ " 200\n" +
+ ")")
+ .contains("withLongAndInt(\n" +
+ " (Integer) 100,\n" +
+ " <any java.lang.Integer>\n" +
+ ")");
}
}
-
+
@Test
- public void shouldNotShowTypesWhenArgumentValueIsDifferent() throws Exception {
+ public void should_not_show_types_when_argument_value_is_different() {
//given
Boo boo = mock(Boo.class);
boo.withLongAndInt(100, 200);
-
+
try {
//when
verify(boo).withLongAndInt(eq(100L), eq(230));
@@ -93,34 +101,34 @@ public void shouldNotShowTypesWhenArgumentValueIsDifferent() throws Exception {
assertContains("withLongAndInt(100, 230)", e.getMessage());
}
}
-
+
class Foo {
-
+
private final int x;
public Foo(int x) {
this.x = x;
}
-
+
public boolean equals(Object obj) {
return x == ((Foo) obj).x;
}
-
+
public int hashCode() {
return 1;
}
-
+
public String toString() {
return "foo";
}
}
-
+
@Test
- public void shouldNotShowTypesWhenTypesAreTheSameEvenIfToStringGivesTheSameResult() throws Exception {
+ public void should_not_show_types_when_types_are_the_same_even_if_to_string_gives_the_same_result() {
//given
IMethods mock = mock(IMethods.class);
mock.simpleMethod(new Foo(10));
-
+
try {
//when
verify(mock).simpleMethod(new Foo(20));
diff --git a/src/test/java/org/mockitoutil/Conditions.java b/src/test/java/org/mockitoutil/Conditions.java
new file mode 100644
index 0000000000..39061cd080
--- /dev/null
+++ b/src/test/java/org/mockitoutil/Conditions.java
@@ -0,0 +1,123 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockitoutil;
+
+import org.assertj.core.api.Assertions;
+import org.assertj.core.api.Condition;
+import org.assertj.core.description.Description;
+import org.assertj.core.description.TextDescription;
+import org.hamcrest.CoreMatchers;
+
+import java.lang.reflect.Method;
+import java.util.Arrays;
+
+@SuppressWarnings("unchecked")
+public class Conditions {
+
+ public static Condition<Throwable> onlyThoseClassesInStackTrace(final String... classes) {
+ return new Condition<Throwable>() {
+ @Override
+ public boolean matches(Throwable traceElements) {
+ StackTraceElement[] trace = traceElements.getStackTrace();
+
+ Assertions.assertThat(trace.length)
+ .describedAs("Number of classes does not match.\nExpected: %s\nGot: %s",
+ Arrays.toString(classes),
+ Arrays.toString(traceElements.getStackTrace()))
+ .isEqualTo(classes.length);
+
+ for (int i = 0; i < trace.length; i++) {
+ Assertions.assertThat(trace[i].getClassName()).isEqualTo(classes[i]);
+ }
+
+ return true;
+ }
+ };
+ }
+
+ public static Condition<StackTraceElement[]> onlyThoseClasses(final String... classes) {
+ return new Condition<StackTraceElement[]>() {
+
+ @Override
+ public boolean matches(StackTraceElement[] traceElements) {
+ Assertions.assertThat(traceElements.length)
+ .describedAs("Number of classes does not match.\nExpected: %s\nGot: %s",
+ Arrays.toString(classes),
+ Arrays.toString(traceElements))
+ .isEqualTo(classes.length);
+
+ for (int i = 0; i < traceElements.length; i++) {
+ Assertions.assertThat(traceElements[i].getClassName()).isEqualTo(classes[i]);
+ }
+
+ return true;
+ }
+ };
+ }
+
+ public static Condition<Throwable> firstMethodInStackTrace(final String method) {
+ return methodInStackTraceAt(0, method);
+ }
+
+ public static Condition<Throwable> methodInStackTraceAt(final int stackTraceIndex, final String method) {
+ return new Condition<Throwable>() {
+ private String actualMethodAtIndex;
+
+ @Override
+ public boolean matches(Throwable throwable) {
+ actualMethodAtIndex = throwable.getStackTrace()[stackTraceIndex].getMethodName();
+
+ return actualMethodAtIndex.equals(method);
+ }
+
+ @Override
+ public Description description() {
+ return new TextDescription("Method at index: %d\nexpected to be: %s\nbut is: %s", stackTraceIndex, method, actualMethodAtIndex);
+ }
+ };
+ }
+
+ public static Condition<Object> bridgeMethod(final String methodName) {
+ return new Condition<Object>() {
+
+ public boolean matches(Object o) {
+ Class<?> clazz = null;
+ if (o instanceof Class) {
+ clazz = (Class<?>) o;
+ } else {
+ clazz = o.getClass();
+ }
+
+ for (Method m : clazz.getMethods()) {
+ if (m.isBridge() && m.getName().equals(methodName)) {
+ return true;
+ }
+ }
+
+ Assertions.fail("Bridge method [" + methodName + "]\nnot found in:\n" + o);
+ return false;
+ }
+ };
+ }
+
+ public static org.hamcrest.Matcher<Object> clazz(Class<?> type) {
+ return CoreMatchers.instanceOf(type);
+ }
+
+ public static Condition<Throwable> methodsInStackTrace(final String... methods) {
+ return new Condition<Throwable>() {
+ public boolean matches(Throwable value) {
+ StackTraceElement[] trace = value.getStackTrace();
+ for (int i = 0; i < methods.length; i++) {
+ Assertions.assertThat(trace[i].getMethodName()).describedAs("Expected methods[%d] to be in the stack trace.", i).isEqualTo(methods[i]);
+ }
+ return true;
+ }
+ };
+ }
+
+
+}
\ No newline at end of file
diff --git a/src/test/java/org/mockitoutil/ExtraMatchers.java b/src/test/java/org/mockitoutil/ExtraMatchers.java
deleted file mode 100644
index c3f80f34c6..0000000000
--- a/src/test/java/org/mockitoutil/ExtraMatchers.java
+++ /dev/null
@@ -1,150 +0,0 @@
-/*
- * Copyright (c) 2007 Mockito contributors
- * This program is made available under the terms of the MIT License.
- */
-
-package org.mockitoutil;
-
-import org.hamcrest.CoreMatchers;
-import org.hamcrest.Matcher;
-
-import java.lang.reflect.Method;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.List;
-
-import static org.junit.Assert.*;
-
-@SuppressWarnings("unchecked")
-public class ExtraMatchers {
-
- public static <T> Assertor<Throwable> hasFirstMethodInStackTrace(final String method) {
- return hasMethodInStackTraceAt(0, method);
- }
-
- public static <T> Assertor<Throwable> hasOnlyThoseClassesInStackTrace(final String ... classes) {
- return new Assertor<Throwable>() {
- public void assertValue(Throwable traceElements) {
- StackTraceElement[] trace = traceElements.getStackTrace();
-
- assertEquals("Number of classes does not match." +
- "\nExpected: " + Arrays.toString(classes) +
- "\nGot: " + Arrays.toString(traceElements.getStackTrace()),
- classes.length, trace.length);
-
- for (int i = 0; i < trace.length; i++) {
- assertEquals(classes[i], trace[i].getClassName());
- }
- }
- };
- }
-
- public static <T> Assertor<StackTraceElement[]> hasOnlyThoseClasses(final String ... classes) {
- return new Assertor<StackTraceElement[]>() {
- public void assertValue(StackTraceElement[] traceElements) {
- assertEquals("Number of classes does not match." +
- "\nExpected: " + Arrays.toString(classes) +
- "\nGot: " + Arrays.toString(traceElements),
- classes.length, traceElements.length);
-
- for (int i = 0; i < traceElements.length; i++) {
- assertEquals(classes[i], traceElements[i].getClassName());
- }
- }
- };
- }
-
- public static <T> Assertor<Throwable> hasMethodInStackTraceAt(final int stackTraceIndex, final String method) {
- return new Assertor<Throwable>() {
-
- private String actualMethodAtIndex;
-
- public void assertValue(Throwable throwable) {
- actualMethodAtIndex = throwable.getStackTrace()[stackTraceIndex].getMethodName();
- assertTrue(
- "Method at index: " + stackTraceIndex +
- "\n" +
- "expected to be: " + method +
- "\n" +
- "but is: " + actualMethodAtIndex,
- actualMethodAtIndex.equals(method));
- }
- };
- }
-
- public static <T> Assertor<Object> hasBridgeMethod(final String methodName) {
- return new Assertor<Object>() {
-
- public void assertValue(Object o) {
- Class<?> clazz = null;
- if (o instanceof Class) {
- clazz = (Class<?>) o;
- } else {
- clazz = o.getClass();
- }
-
- for (Method m : clazz.getMethods()) {
- if (m.isBridge() && m.getName().equals(methodName)) {
- return;
- }
- }
-
- fail("Bridge method [" + methodName + "]\nnot found in:\n" + o);
- }
- };
- }
-
- public static <T> Assertor<Collection> hasExactlyInOrder(final T ... elements) {
- return new Assertor<Collection>() {
-
- public void assertValue(Collection value) {
- assertEquals(elements.length, value.size());
-
- boolean containsSublist = Collections.indexOfSubList((List<?>) value, Arrays.asList(elements)) != -1;
- assertTrue(
- "Elements:" +
- "\n" +
- Arrays.toString(elements) +
- "\n" +
- "were not found in collection:" +
- "\n" +
- value, containsSublist);
- }
- };
- }
-
- public static <T> Assertor<Collection> contains(final Matcher<T> ... elements) {
- return new Assertor<Collection>() {
-
- public void assertValue(Collection value) {
- int matched = 0;
- for (Matcher<T> m : elements) {
- for (Object el : value) {
- if (m.matches(el)) {
- matched++;
- continue;
- }
- }
- }
-
- assertEquals("At least one of the matchers failed to match any of the elements", elements.length, matched);
- }
- };
- }
-
- public static org.hamcrest.Matcher<Object> clazz(Class<?> type) {
- return CoreMatchers.instanceOf(type);
- }
-
- public static Assertor<Throwable> hasMethodsInStackTrace(final String ... methods) {
- return new Assertor<Throwable>() {
- public void assertValue(Throwable value) {
- StackTraceElement[] trace = value.getStackTrace();
- for (int i = 0; i < methods.length; i++) {
- assertEquals("Expected methods[" + i + "] to be in the stack trace.", methods[i], trace[i].getMethodName());
- }
- }
- };
- }
-}
\ No newline at end of file
diff --git a/src/test/java/org/mockitoutil/JUnitResultAssert.java b/src/test/java/org/mockitoutil/JUnitResultAssert.java
index f4fd9f9769..8a425a91c6 100644
--- a/src/test/java/org/mockitoutil/JUnitResultAssert.java
+++ b/src/test/java/org/mockitoutil/JUnitResultAssert.java
@@ -2,7 +2,6 @@
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
-import org.mockito.exceptions.misusing.UnnecessaryStubbingException;
import java.util.List;
@@ -57,4 +56,11 @@ private static String formatFailures(List<Failure> failures) {
}
return out.toString();
}
+
+ /**
+ * Clean assertions for JUnit's result object
+ */
+ public static JUnitResultAssert assertThat(Result result) {
+ return new JUnitResultAssert(result);
+ }
}
diff --git a/src/test/java/org/mockitoutil/TestBase.java b/src/test/java/org/mockitoutil/TestBase.java
index 9ad32341bd..348e12f060 100644
--- a/src/test/java/org/mockitoutil/TestBase.java
+++ b/src/test/java/org/mockitoutil/TestBase.java
@@ -5,10 +5,8 @@
package org.mockitoutil;
-import org.hamcrest.Matcher;
import org.junit.After;
import org.junit.Before;
-import org.junit.runner.Result;
import org.mockito.MockitoAnnotations;
import org.mockito.StateMaster;
import org.mockito.internal.MockitoCore;
@@ -26,7 +24,6 @@
import java.io.IOException;
import java.io.PrintStream;
import java.util.Collection;
-import java.util.regex.Pattern;
import static junit.framework.TestCase.assertFalse;
import static junit.framework.TestCase.assertTrue;
@@ -68,29 +65,6 @@ protected Invocation getLastInvocation() {
return new MockitoCore().getLastInvocation();
}
- //I'm really tired of matchers, enter the assertor!
- protected static <T> void assertThat(T o, Assertor<T> a) {
- a.assertValue(o);
- }
-
- protected static <T> void assertThat(T actual, Matcher<? super T> matcher) {
- org.junit.Assert.assertThat(actual, matcher);
- }
-
- protected static <T> void assertThat(String message, T actual, Matcher<T> m) {
- org.junit.Assert.assertThat(message, actual, m);
- }
-
- public static <T> Assertor<String> endsWith(final String substring) {
- return new Assertor<String>() {
- public void assertValue(String value) {
- assertTrue("This substring: \n" + substring +
- "\nshould be at the end of:\n" + value
- , value.endsWith(substring));
- }
- };
- }
-
public static void assertNotEquals(Object expected, Object got) {
assertFalse(expected.equals(got));
}
@@ -201,11 +175,4 @@ protected String getStackTrace(Throwable e) {
protected String filterLineNo(String stackTrace) {
return stackTrace.replaceAll("(\\((\\w+\\.java):(\\d)+\\))", "($2:0)");
}
-
- /**
- * Clean assertions for JUnit's result object
- */
- protected JUnitResultAssert assertThat(Result result) {
- return new JUnitResultAssert(result);
- }
}
| train | train | 2016-07-28T03:59:24 | "2015-04-05T10:23:55Z" | bric3 | train |
mockito/mockito/497_549 | mockito/mockito | mockito/mockito/497 | mockito/mockito/549 | [
"keyword_pr_to_issue"
] | 4ce9ac2ea38153f4f0c7e272d52fdf9a494ccb14 | 27bcbbb03709b23d0efaa300dab6cd5b9d345a83 | [
"I have a hacky workaround using Guava's `TypeToken`:\n\n```\n private static final MockUtil mockUtil = new MockUtil();\n\n @SuppressWarnings(\"unchecked\")\n private static <T> T createSmartDeepMock(TypeToken<T> mockType) {\n return (T) mock(mockType.getRawType(), createSmartDeepMockAnswer(mockType));\n }\n\n private static Answer<?> createSmartDeepMockAnswer(TypeToken<?> mockType) {\n Map<Method, Object> mocks = new LinkedHashMap<>();\n\n return invocation -> {\n Method method = invocation.getMethod();\n if (mocks.containsKey(method)) {\n return mocks.get(method);\n }\n\n Type returnType = method.getGenericReturnType();\n TypeToken<?> resolvedReturnType = mockType.resolveType(returnType);\n Class<?> returnClass = resolvedReturnType.getRawType();\n\n if (!mockUtil.isTypeMockable(returnClass)) {\n return Mockito.RETURNS_DEFAULTS.answer(invocation);\n } else {\n Object mock = createSmartDeepMock(resolvedReturnType);\n mocks.put(method, mock);\n return mock;\n }\n };\n }\n```\n"
] | [
"Codecov complains about not testing this path. I don't think this line is required per https://github.com/JeffreyFalgout/mockito/blob/b4b5b0be26aaf6218cd5b8253faf03e2d116bdb8/src/main/java/org/mockito/internal/util/reflection/GenericMetadataSupport.java#L272-L273 which handles the `instanceof` checks in `inferFrom` which is the only method that uses the `FromParameterizedTypeGenericMetadataSupport`.\n",
"This else clause is always when `clazz instanceof Class` so this Exception is not required. See above comment.\n",
"@JeffreyFalgout \n- Can this really happen? If yes more error infos would be usefule? E.g. \"Unable to determine the raw type of \"+type.\n- just a matter of style the `else` keywords can be removed\n",
"@TimvdLippe Haha i commented about the same in just the same minute!\n",
"Done.\n"
] | "2016-08-12T03:36:03Z" | [] | DEEP_STUBS tries to mock final class | ```
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>1.10.19</version>
<scope>test</scope>
</dependency>
```
```
$ java -version
java version "1.8.0_91"
Java(TM) SE Runtime Environment (build 1.8.0_91-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.91-b14, mixed mode)
```
```
import static org.junit.Assert.assertNull;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import org.junit.Test;
public class MockitoBug {
public interface Supplier<T> {
public T get();
}
public interface StringSupplier extends Supplier<String> {}
public interface InheritedSupplier extends StringSupplier {}
@Test
public void deepStubs() {
StringSupplier mock = mock(StringSupplier.class, RETURNS_DEEP_STUBS);
String s = mock.get();
assertNull(s);
}
@Test
public void inheritedDeepStubs() {
InheritedSupplier mock = mock(InheritedSupplier.class, RETURNS_DEEP_STUBS);
String s = mock.get(); // ClassCastException
assertNull(s);
}
}
```
```
java.lang.ClassCastException: org.mockito.internal.creation.cglib.ClassImposterizer$ClassWithSuperclassToWorkAroundCglibBug$$EnhancerByMockitoWithCGLIB$$322ebf6e cannot be cast to java.lang.String
at MockitoBug.inheritedDeepStubs(MockitoBug.java:26)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
```
I expect the behavior for `StringSupplier` and `InheritedSupplier` to be the same: return `null` for `get`. However, `InheritedSupplier` tries to return a mock `Object` for `get`.
| [
"src/main/java/org/mockito/internal/util/reflection/GenericMetadataSupport.java"
] | [
"src/main/java/org/mockito/internal/util/reflection/GenericMetadataSupport.java"
] | [
"src/test/java/org/mockito/internal/stubbing/defaultanswers/ReturnsGenericDeepStubsTest.java",
"src/test/java/org/mockito/internal/util/reflection/GenericMetadataSupportTest.java"
] | diff --git a/src/main/java/org/mockito/internal/util/reflection/GenericMetadataSupport.java b/src/main/java/org/mockito/internal/util/reflection/GenericMetadataSupport.java
index 50baa3c2f6..8d150ff787 100644
--- a/src/main/java/org/mockito/internal/util/reflection/GenericMetadataSupport.java
+++ b/src/main/java/org/mockito/internal/util/reflection/GenericMetadataSupport.java
@@ -62,6 +62,48 @@ public abstract class GenericMetadataSupport {
*/
protected Map<TypeVariable, Type> contextualActualTypeParameters = new HashMap<TypeVariable, Type>();
+ /**
+ * Registers the type variables for the given type and all of its superclasses and superinterfaces.
+ */
+ protected void registerAllTypeVariables(Type classType) {
+ Queue<Type> typesToRegister = new LinkedList<Type>();
+ Set<Type> registeredTypes = new HashSet<Type>();
+ typesToRegister.add(classType);
+
+ while (!typesToRegister.isEmpty()) {
+ Type typeToRegister = typesToRegister.poll();
+ if (typeToRegister == null || registeredTypes.contains(typeToRegister)) {
+ continue;
+ }
+
+ registerTypeVariablesOn(typeToRegister);
+ registeredTypes.add(typeToRegister);
+
+ Class<?> rawType = extractRawTypeOf(typeToRegister);
+ typesToRegister.add(rawType.getGenericSuperclass());
+ typesToRegister.addAll(Arrays.asList(rawType.getGenericInterfaces()));
+ }
+ }
+
+ protected Class<?> extractRawTypeOf(Type type) {
+ if (type instanceof Class) {
+ return (Class<?>) type;
+ }
+ if (type instanceof ParameterizedType) {
+ return (Class<?>) ((ParameterizedType) type).getRawType();
+ }
+ if (type instanceof BoundedType) {
+ return extractRawTypeOf(((BoundedType) type).firstBound());
+ }
+ if (type instanceof TypeVariable) {
+ /*
+ * If type is a TypeVariable, then it is needed to gather data elsewhere. Usually TypeVariables are declared
+ * on the class definition, such as such as List<E>.
+ */
+ return extractRawTypeOf(contextualActualTypeParameters.get(type));
+ }
+ throw new MockitoException("Raw extraction not supported for : '" + type + "'");
+ }
protected void registerTypeVariablesOn(Type classType) {
if (!(classType instanceof ParameterizedType)) {
@@ -270,28 +312,8 @@ private static class FromClassGenericMetadataSupport extends GenericMetadataSupp
public FromClassGenericMetadataSupport(Class<?> clazz) {
this.clazz = clazz;
- for (Class<?> currentExploredClass = clazz;
- currentExploredClass != null && currentExploredClass != Object.class;
- currentExploredClass = superClassOf(currentExploredClass)) {
- readActualTypeParametersOnDeclaringClass(currentExploredClass);
- }
- }
-
- private Class superClassOf(Class<?> currentExploredClass) {
- Type genericSuperclass = currentExploredClass.getGenericSuperclass();
- if (genericSuperclass instanceof ParameterizedType) {
- Type rawType = ((ParameterizedType) genericSuperclass).getRawType();
- return (Class<?>) rawType;
- }
- return (Class<?>) genericSuperclass;
- }
-
- private void readActualTypeParametersOnDeclaringClass(Class<?> clazz) {
registerTypeParametersOn(clazz.getTypeParameters());
- registerTypeVariablesOn(clazz.getGenericSuperclass());
- for (Type genericInterface : clazz.getGenericInterfaces()) {
- registerTypeVariablesOn(genericInterface);
- }
+ registerAllTypeVariables(clazz);
}
@Override
@@ -321,8 +343,7 @@ public FromParameterizedTypeGenericMetadataSupport(ParameterizedType parameteriz
}
private void readActualTypeParameters() {
- registerTypeVariablesOn(parameterizedType.getRawType());
- registerTypeVariablesOn(parameterizedType);
+ registerAllTypeVariables(parameterizedType);
}
@Override
@@ -403,26 +424,6 @@ public Class<?> rawType() {
return rawType;
}
- private Class<?> extractRawTypeOf(Type type) {
- if (type instanceof Class) {
- return (Class<?>) type;
- }
- if (type instanceof ParameterizedType) {
- return (Class<?>) ((ParameterizedType) type).getRawType();
- }
- if (type instanceof BoundedType) {
- return extractRawTypeOf(((BoundedType) type).firstBound());
- }
- if (type instanceof TypeVariable) {
- /*
- * If type is a TypeVariable, then it is needed to gather data elsewhere. Usually TypeVariables are declared
- * on the class definition, such as such as List<E>.
- */
- return extractRawTypeOf(contextualActualTypeParameters.get(type));
- }
- throw new MockitoException("Raw extraction not supported for : '" + type + "'");
- }
-
@Override
public List<Type> extraInterfaces() {
Type type = extractActualBoundedTypeOf(typeVariable);
| diff --git a/src/test/java/org/mockito/internal/stubbing/defaultanswers/ReturnsGenericDeepStubsTest.java b/src/test/java/org/mockito/internal/stubbing/defaultanswers/ReturnsGenericDeepStubsTest.java
index 44066b8ced..f580b359a3 100644
--- a/src/test/java/org/mockito/internal/stubbing/defaultanswers/ReturnsGenericDeepStubsTest.java
+++ b/src/test/java/org/mockito/internal/stubbing/defaultanswers/ReturnsGenericDeepStubsTest.java
@@ -19,6 +19,8 @@
public class ReturnsGenericDeepStubsTest {
interface ListOfInteger extends List<Integer> {}
+ interface AnotherListOfInteger extends ListOfInteger {}
+
interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {
Set<Number> remove(Object key); // override with fixed ParameterizedType
List<? super Number> returningWildcard();
@@ -93,9 +95,11 @@ public void can_still_work_with_raw_type_in_the_return_type() throws Exception {
public void will_return_default_value_on_non_mockable_nested_generic() throws Exception {
GenericsNest<?> genericsNest = mock(GenericsNest.class, RETURNS_DEEP_STUBS);
ListOfInteger listOfInteger = mock(ListOfInteger.class, RETURNS_DEEP_STUBS);
+ AnotherListOfInteger anotherListOfInteger = mock(AnotherListOfInteger.class, RETURNS_DEEP_STUBS);
assertThat(genericsNest.returningNonMockableNestedGeneric().keySet().iterator().next()).isNull();
assertThat(listOfInteger.get(25)).isEqualTo(0);
+ assertThat(anotherListOfInteger.get(25)).isEqualTo(0);
}
@Test(expected = ClassCastException.class)
diff --git a/src/test/java/org/mockito/internal/util/reflection/GenericMetadataSupportTest.java b/src/test/java/org/mockito/internal/util/reflection/GenericMetadataSupportTest.java
index d068e043d5..dff0d7f3ea 100644
--- a/src/test/java/org/mockito/internal/util/reflection/GenericMetadataSupportTest.java
+++ b/src/test/java/org/mockito/internal/util/reflection/GenericMetadataSupportTest.java
@@ -28,6 +28,11 @@ interface UpperBoundedTypeWithInterfaces<E extends Comparable<E> & Cloneable> {
E get();
}
interface ListOfNumbers extends List<Number> {}
+ interface AnotherListOfNumbers extends ListOfNumbers {}
+
+ abstract class ListOfNumbersImpl implements ListOfNumbers {}
+ abstract class AnotherListOfNumbersImpl extends ListOfNumbersImpl {}
+
interface ListOfAnyNumbers<N extends Number & Cloneable> extends List<N> {}
interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {
@@ -76,6 +81,13 @@ public void can_get_type_variables_from_Class() throws Exception {
assertThat(inferFrom(StringList.class).actualTypeArguments().keySet()).isEmpty();
}
+ @Test
+ public void can_resolve_type_variables_from_ancestors() throws Exception {
+ Method listGet = List.class.getMethod("get", int.class);
+ assertThat(inferFrom(AnotherListOfNumbers.class).resolveGenericReturnType(listGet).rawType()).isEqualTo(Number.class);
+ assertThat(inferFrom(AnotherListOfNumbersImpl.class).resolveGenericReturnType(listGet).rawType()).isEqualTo(Number.class);
+ }
+
@Test
public void can_get_type_variables_from_ParameterizedType() throws Exception {
assertThat(inferFrom(GenericsNest.class.getGenericInterfaces()[0]).actualTypeArguments().keySet()).hasSize(2).extracting("name").contains("K", "V");
| train | train | 2016-08-15T15:27:39 | "2016-07-16T17:59:01Z" | JeffFaer | train |
mockito/mockito/538_550 | mockito/mockito | mockito/mockito/538 | mockito/mockito/550 | [
"keyword_pr_to_issue"
] | f80dd4a95d78d15dfea814877d143e8e31cfd880 | fea4074f8d4a7b1f7b8e89d4819bef25b1b6228f | [] | [
"Please don't remove these indication, lot of people would like to see this.\n"
] | "2016-08-12T20:46:56Z" | [] | Improve error message when @InjectMocks is uses on an interface or enum field | By accident a tests delares a field of an interface type instead of the implementing class.
```
@InjectMocks
public InterfaceType unitUnderTest;
```
Injection is not possible on interfaces or enums. The error message should make this clear, the currenta message that doesn't help much:
```
org.mockito.exceptions.base.MockitoException:
Cannot instantiate @InjectMocks field named 'configurationManager'.
You haven't provided the instance at field declaration so I tried to construct the instance.
However, I failed because: the type 'ConfigurationManager' is an interface.
Examples of correct usage of @InjectMocks:
@InjectMocks Service service = new Service();
@InjectMocks Service service;
//also, don't forget about MockitoAnnotations.initMocks();
//and... don't forget about some @Mocks for injection :)
```
The error message should be someting like:
`The field 'unitUnderTest' can not be annotated with @InjectMocks cause the type 'InterfaceType ' not a class!
`
| [
"src/main/java/org/mockito/internal/configuration/injection/PropertyAndSetterInjection.java",
"src/main/java/org/mockito/internal/exceptions/Reporter.java",
"src/main/java/org/mockito/internal/util/reflection/FieldInitializer.java"
] | [
"src/main/java/org/mockito/internal/configuration/injection/PropertyAndSetterInjection.java",
"src/main/java/org/mockito/internal/exceptions/Reporter.java",
"src/main/java/org/mockito/internal/util/reflection/FieldInitializer.java"
] | [
"src/test/java/org/mockitousage/annotation/MockInjectionUsingConstructorTest.java",
"src/test/java/org/mockitousage/basicapi/MocksCreationTest.java"
] | diff --git a/src/main/java/org/mockito/internal/configuration/injection/PropertyAndSetterInjection.java b/src/main/java/org/mockito/internal/configuration/injection/PropertyAndSetterInjection.java
index 92e5868913..5b52a71262 100644
--- a/src/main/java/org/mockito/internal/configuration/injection/PropertyAndSetterInjection.java
+++ b/src/main/java/org/mockito/internal/configuration/injection/PropertyAndSetterInjection.java
@@ -98,7 +98,7 @@ private FieldInitializationReport initializeInjectMocksField(Field field, Object
Throwable realCause = e.getCause().getCause();
throw fieldInitialisationThrewException(field, realCause);
}
- throw cannotInitializeForInjectMocksAnnotation(field.getName(), e);
+ throw cannotInitializeForInjectMocksAnnotation(field.getName(),e.getMessage());
}
}
diff --git a/src/main/java/org/mockito/internal/exceptions/Reporter.java b/src/main/java/org/mockito/internal/exceptions/Reporter.java
index 3a63d69ddc..8a28e67f89 100644
--- a/src/main/java/org/mockito/internal/exceptions/Reporter.java
+++ b/src/main/java/org/mockito/internal/exceptions/Reporter.java
@@ -627,16 +627,14 @@ public static MockitoException cannotInitializeForSpyAnnotation(String fieldName
""), details);
}
- public static MockitoException cannotInitializeForInjectMocksAnnotation(String fieldName, Exception details) {
- return new MockitoException(join("Cannot instantiate @InjectMocks field named '" + fieldName + "'.",
+ public static MockitoException cannotInitializeForInjectMocksAnnotation(String fieldName, String causeMessage) {
+ return new MockitoException(join("Cannot instantiate @InjectMocks field named '" + fieldName + "'! Cause: "+causeMessage,
"You haven't provided the instance at field declaration so I tried to construct the instance.",
- "However, I failed because: " + details.getMessage(),
"Examples of correct usage of @InjectMocks:",
" @InjectMocks Service service = new Service();",
" @InjectMocks Service service;",
- " //also, don't forget about MockitoAnnotations.initMocks();",
" //and... don't forget about some @Mocks for injection :)",
- ""), details);
+ ""));
}
public static MockitoException atMostAndNeverShouldNotBeUsedWithTimeout() {
diff --git a/src/main/java/org/mockito/internal/util/reflection/FieldInitializer.java b/src/main/java/org/mockito/internal/util/reflection/FieldInitializer.java
index 7a49e1f6b5..fdc6975498 100644
--- a/src/main/java/org/mockito/internal/util/reflection/FieldInitializer.java
+++ b/src/main/java/org/mockito/internal/util/reflection/FieldInitializer.java
@@ -7,6 +7,7 @@
import org.mockito.exceptions.base.MockitoException;
import org.mockito.internal.util.MockUtil;
+import static java.lang.reflect.Modifier.isStatic;
import static org.mockito.internal.util.reflection.FieldSetter.setField;
import java.lang.reflect.Constructor;
@@ -68,7 +69,9 @@ private FieldInitializer(Object fieldOwner, Field field, ConstructorInstantiator
checkNotLocal(field);
checkNotInner(field);
checkNotInterface(field);
+ checkNotEnum(field);
checkNotAbstract(field);
+
}
this.fieldOwner = fieldOwner;
this.field = field;
@@ -100,8 +103,9 @@ private void checkNotLocal(Field field) {
}
private void checkNotInner(Field field) {
- if(field.getType().isMemberClass() && !Modifier.isStatic(field.getType().getModifiers())) {
- throw new MockitoException("the type '" + field.getType().getSimpleName() + "' is an inner class.");
+ Class<?> type = field.getType();
+ if(type.isMemberClass() && !isStatic(type.getModifiers())) {
+ throw new MockitoException("the type '" + type.getSimpleName() + "' is an inner non static class.");
}
}
@@ -113,10 +117,17 @@ private void checkNotInterface(Field field) {
private void checkNotAbstract(Field field) {
if(Modifier.isAbstract(field.getType().getModifiers())) {
- throw new MockitoException("the type '" + field.getType().getSimpleName() + " is an abstract class.");
+ throw new MockitoException("the type '" + field.getType().getSimpleName() + "' is an abstract class.");
+ }
+ }
+
+ private void checkNotEnum(Field field) {
+ if(field.getType().isEnum()) {
+ throw new MockitoException("the type '" + field.getType().getSimpleName() + "' is an enum.");
}
}
+
private FieldInitializationReport acquireFieldInstance() throws IllegalAccessException {
Object fieldInstance = field.get(fieldOwner);
if(fieldInstance != null) {
| diff --git a/src/test/java/org/mockitousage/annotation/MockInjectionUsingConstructorTest.java b/src/test/java/org/mockitousage/annotation/MockInjectionUsingConstructorTest.java
index 4ae5590012..a11a3a7332 100644
--- a/src/test/java/org/mockitousage/annotation/MockInjectionUsingConstructorTest.java
+++ b/src/test/java/org/mockitousage/annotation/MockInjectionUsingConstructorTest.java
@@ -5,9 +5,24 @@
package org.mockitousage.annotation;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+import static org.mockito.Mockito.when;
+import static org.mockito.MockitoAnnotations.initMocks;
+
+import java.util.AbstractCollection;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import org.assertj.core.api.Assertions;
import org.junit.Ignore;
+import org.junit.Rule;
import org.junit.Test;
import org.junit.internal.TextListener;
+import org.junit.rules.ExpectedException;
import org.junit.runner.JUnitCore;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
@@ -17,17 +32,11 @@
import org.mockito.exceptions.base.MockitoException;
import org.mockito.internal.util.MockUtil;
import org.mockito.runners.MockitoJUnitRunner;
+import org.mockitousage.IMethods;
import org.mockitousage.examples.use.ArticleCalculator;
import org.mockitousage.examples.use.ArticleDatabase;
import org.mockitousage.examples.use.ArticleManager;
-import java.util.List;
-import java.util.Set;
-
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.junit.Assert.*;
-import static org.mockito.Mockito.when;
-
@RunWith(MockitoJUnitRunner.class)
public class MockInjectionUsingConstructorTest {
@@ -37,8 +46,8 @@ public class MockInjectionUsingConstructorTest {
@InjectMocks private ArticleManager articleManager;
@Spy @InjectMocks private ArticleManager spiedArticleManager;
-
-// @InjectMocks private ArticleVisitor should_be_initialized_3_times;
+ @Rule
+ public ExpectedException exception = ExpectedException.none();
@Test
public void shouldNotFailWhenNotInitialized() {
@@ -120,5 +129,91 @@ private static class ATest {
@InjectMocks FailingConstructor failingConstructor;
}
+
+ @Test
+ public void injectMocksMustFailWithInterface() throws Exception {
+ class TestCase {
+ @InjectMocks
+ IMethods f;
+ }
+
+ exception.expect(MockitoException.class);
+ exception.expectMessage("Cannot instantiate @InjectMocks field named 'f'! Cause: the type 'IMethods' is an interface");
+
+
+ initMocks(new TestCase());
+ }
+
+ @Test
+ public void injectMocksMustFailWithEnum() throws Exception {
+ class TestCase {
+ @InjectMocks
+ TimeUnit f;
+ }
+
+ exception.expect(MockitoException.class);
+ exception.expectMessage("Cannot instantiate @InjectMocks field named 'f'! Cause: the type 'TimeUnit' is an enum");
+
+ initMocks(new TestCase());
+ }
+
+ @Test
+ public void injectMocksMustFailWithAbstractClass() throws Exception {
+ class TestCase {
+ @InjectMocks
+ AbstractCollection<?> f;
+ }
+
+ exception.expect(MockitoException.class);
+ exception.expectMessage("Cannot instantiate @InjectMocks field named 'f'! Cause: the type 'AbstractCollection' is an abstract class");
+
+ initMocks(new TestCase());
+ }
+
+ @Test
+ public void injectMocksMustFailWithNonStaticInnerClass() throws Exception {
+ class TestCase {
+ class InnerClass {}
+ @InjectMocks
+ InnerClass f;
+ }
+
+
+ exception.expect(MockitoException.class);
+ exception.expectMessage("Cannot instantiate @InjectMocks field named 'f'! Cause: the type 'InnerClass' is an inner non static class");
+
+ initMocks(new TestCase());
+ }
+
+ static class StaticInnerClass {}
+ @Test
+ public void injectMocksMustSucceedWithStaticInnerClass() throws Exception {
+ class TestCase {
+ @InjectMocks
+ StaticInnerClass f;
+ }
+
+ TestCase testClass = new TestCase();
+ initMocks(testClass);
+
+ assertThat(testClass.f).isInstanceOf(StaticInnerClass.class);
+ }
+
+ @Test
+ public void injectMocksMustSucceedWithInstance() throws Exception {
+ class TestCase {
+ @InjectMocks
+ StaticInnerClass f = new StaticInnerClass();
+ }
+
+ TestCase testClass = new TestCase();
+ StaticInnerClass original = testClass.f;
+ initMocks(testClass);
+
+ assertThat(testClass.f).isSameAs(original);
+ }
+
+
+
}
diff --git a/src/test/java/org/mockitousage/basicapi/MocksCreationTest.java b/src/test/java/org/mockitousage/basicapi/MocksCreationTest.java
index 7d6ae465ba..5915fe71cd 100644
--- a/src/test/java/org/mockitousage/basicapi/MocksCreationTest.java
+++ b/src/test/java/org/mockitousage/basicapi/MocksCreationTest.java
@@ -6,7 +6,9 @@
package org.mockitousage.basicapi;
import org.junit.Test;
+import org.mockito.InjectMocks;
import org.mockito.Mockito;
+import org.mockito.MockitoAnnotations;
import org.mockito.exceptions.base.MockitoException;
import org.mockito.exceptions.verification.SmartNullPointerException;
import org.mockito.internal.debugging.LocationImpl;
@@ -16,6 +18,7 @@
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
+import java.util.concurrent.TimeUnit;
import static junit.framework.TestCase.*;
import static org.assertj.core.api.Assertions.assertThat;
| train | train | 2016-08-13T20:05:32 | "2016-08-09T14:00:29Z" | ChristianSchwarz | train |
mockito/mockito/551_556 | mockito/mockito | mockito/mockito/551 | mockito/mockito/556 | [
"keyword_pr_to_issue"
] | 4ce9ac2ea38153f4f0c7e272d52fdf9a494ccb14 | 669a05c1dcc6423ae15d5cf04f40720e3a8f0765 | [
"`VerificationCollectorImpl` is package-protected and is not generated in the Javadoc either: http://site.mockito.org/mockito/docs/current/org/mockito/junit/package-summary.html\n\nThe other `VerificationWrapper`s can be package-protected too.\n",
"This is a good point!\n\nI suggest we move it to internal package anyway. This way:\n- it is consistent how we manage public / private API\n- it can be used more easily by devs who experiment / hack (e.g. they know what they are doing when using private API :)\n- it is less error prone (e.g. when someone forgets to remove 'public' or when someone adds 'public' not realizing consequences)\n"
] | [] | "2016-08-15T14:42:45Z" | [] | Unexpected new public API: VerificationWrapper, VerificationWrapperInOrder, VerificationCollectorImpl | It looks like some classes leaked to the public API: VerificationWrapper, VerificationWrapperInOrder, VerificationCollectorImpl
They seem like internal classes because:
a) they are concrete implementation where public API should be an interface
b) no javadoc
c) looking at their API, they don't seem like something we want to expose to the users :)
We need to fix it before 2.0, perhaps it's just the matter of moving it to internal packages.
| [
"src/main/java/org/mockito/internal/InOrderImpl.java",
"src/main/java/org/mockito/junit/VerificationCollectorImpl.java",
"src/main/java/org/mockito/verification/VerificationWrapper.java",
"src/main/java/org/mockito/verification/VerificationWrapperInOrderWrapper.java",
"src/main/java/org/mockito/junit/MockitoJUnit.java",
"src/main/java/org/mockito/verification/After.java",
"src/main/java/org/mockito/verification/Timeout.java"
] | [
"src/main/java/org/mockito/internal/InOrderImpl.java",
"src/main/java/org/mockito/internal/junit/VerificationCollectorImpl.java",
"src/main/java/org/mockito/internal/verification/VerificationWrapper.java",
"src/main/java/org/mockito/internal/verification/VerificationWrapperInOrderWrapper.java",
"src/main/java/org/mockito/junit/MockitoJUnit.java",
"src/main/java/org/mockito/verification/After.java",
"src/main/java/org/mockito/verification/Timeout.java"
] | [] | diff --git a/src/main/java/org/mockito/internal/InOrderImpl.java b/src/main/java/org/mockito/internal/InOrderImpl.java
index cb3442f373..ce37b23da4 100644
--- a/src/main/java/org/mockito/internal/InOrderImpl.java
+++ b/src/main/java/org/mockito/internal/InOrderImpl.java
@@ -14,8 +14,8 @@
import org.mockito.internal.verification.api.VerificationInOrderMode;
import org.mockito.invocation.Invocation;
import org.mockito.verification.VerificationMode;
-import org.mockito.verification.VerificationWrapper;
-import org.mockito.verification.VerificationWrapperInOrderWrapper;
+import org.mockito.internal.verification.VerificationWrapper;
+import org.mockito.internal.verification.VerificationWrapperInOrderWrapper;
import static org.mockito.internal.exceptions.Reporter.inOrderRequiresFamiliarMock;
diff --git a/src/main/java/org/mockito/junit/VerificationCollectorImpl.java b/src/main/java/org/mockito/internal/junit/VerificationCollectorImpl.java
similarity index 94%
rename from src/main/java/org/mockito/junit/VerificationCollectorImpl.java
rename to src/main/java/org/mockito/internal/junit/VerificationCollectorImpl.java
index b1ffeb8946..da9c4515f6 100644
--- a/src/main/java/org/mockito/junit/VerificationCollectorImpl.java
+++ b/src/main/java/org/mockito/internal/junit/VerificationCollectorImpl.java
@@ -1,4 +1,4 @@
-package org.mockito.junit;
+package org.mockito.internal.junit;
import static org.mockito.internal.progress.ThreadSafeMockingProgress.mockingProgress;
@@ -7,18 +7,19 @@
import org.mockito.exceptions.base.MockitoAssertionError;
import org.mockito.internal.progress.MockingProgressImpl;
import org.mockito.internal.verification.api.VerificationData;
+import org.mockito.junit.VerificationCollector;
import org.mockito.verification.VerificationMode;
import org.mockito.verification.VerificationStrategy;
/**
* Mockito implementation of VerificationCollector.
*/
-class VerificationCollectorImpl implements VerificationCollector {
+public class VerificationCollectorImpl implements VerificationCollector {
private StringBuilder builder;
private int numberOfFailures;
- VerificationCollectorImpl() {
+ public VerificationCollectorImpl() {
this.resetBuilder();
}
diff --git a/src/main/java/org/mockito/verification/VerificationWrapper.java b/src/main/java/org/mockito/internal/verification/VerificationWrapper.java
similarity index 93%
rename from src/main/java/org/mockito/verification/VerificationWrapper.java
rename to src/main/java/org/mockito/internal/verification/VerificationWrapper.java
index d32fab221d..13ad8d8164 100644
--- a/src/main/java/org/mockito/verification/VerificationWrapper.java
+++ b/src/main/java/org/mockito/internal/verification/VerificationWrapper.java
@@ -1,7 +1,7 @@
-package org.mockito.verification;
+package org.mockito.internal.verification;
-import org.mockito.internal.verification.VerificationModeFactory;
import org.mockito.internal.verification.api.VerificationData;
+import org.mockito.verification.VerificationMode;
public abstract class VerificationWrapper<WrapperType extends VerificationMode> implements VerificationMode {
diff --git a/src/main/java/org/mockito/verification/VerificationWrapperInOrderWrapper.java b/src/main/java/org/mockito/internal/verification/VerificationWrapperInOrderWrapper.java
similarity index 91%
rename from src/main/java/org/mockito/verification/VerificationWrapperInOrderWrapper.java
rename to src/main/java/org/mockito/internal/verification/VerificationWrapperInOrderWrapper.java
index e04cfd749d..f04ebadbfb 100644
--- a/src/main/java/org/mockito/verification/VerificationWrapperInOrderWrapper.java
+++ b/src/main/java/org/mockito/internal/verification/VerificationWrapperInOrderWrapper.java
@@ -1,12 +1,10 @@
-package org.mockito.verification;
+package org.mockito.internal.verification;
import org.mockito.exceptions.base.MockitoException;
import org.mockito.internal.InOrderImpl;
-import org.mockito.internal.verification.InOrderWrapper;
-import org.mockito.internal.verification.VerificationModeFactory;
-import org.mockito.internal.verification.VerificationOverTimeImpl;
import org.mockito.internal.verification.api.VerificationData;
import org.mockito.internal.verification.api.VerificationInOrderMode;
+import org.mockito.verification.VerificationMode;
public class VerificationWrapperInOrderWrapper implements VerificationMode {
private final VerificationMode delegate;
diff --git a/src/main/java/org/mockito/junit/MockitoJUnit.java b/src/main/java/org/mockito/junit/MockitoJUnit.java
index 8c6c32ea6e..fac86b4572 100644
--- a/src/main/java/org/mockito/junit/MockitoJUnit.java
+++ b/src/main/java/org/mockito/junit/MockitoJUnit.java
@@ -1,6 +1,7 @@
package org.mockito.junit;
import org.mockito.internal.junit.JUnitRule;
+import org.mockito.internal.junit.VerificationCollectorImpl;
import org.mockito.internal.util.ConsoleMockitoLogger;
/**
diff --git a/src/main/java/org/mockito/verification/After.java b/src/main/java/org/mockito/verification/After.java
index cc63dfbfd5..089324ebcc 100644
--- a/src/main/java/org/mockito/verification/After.java
+++ b/src/main/java/org/mockito/verification/After.java
@@ -2,6 +2,7 @@
import org.mockito.internal.verification.VerificationModeFactory;
import org.mockito.internal.verification.VerificationOverTimeImpl;
+import org.mockito.internal.verification.VerificationWrapper;
/**
* See the javadoc for {@link VerificationAfterDelay}
diff --git a/src/main/java/org/mockito/verification/Timeout.java b/src/main/java/org/mockito/verification/Timeout.java
index dcb8b46c9b..f49765a270 100644
--- a/src/main/java/org/mockito/verification/Timeout.java
+++ b/src/main/java/org/mockito/verification/Timeout.java
@@ -9,6 +9,7 @@
import org.mockito.internal.util.Timer;
import org.mockito.internal.verification.VerificationModeFactory;
import org.mockito.internal.verification.VerificationOverTimeImpl;
+import org.mockito.internal.verification.VerificationWrapper;
/**
* See the javadoc for {@link VerificationWithTimeout}
| null | train | train | 2016-08-15T15:27:39 | "2016-08-13T15:17:16Z" | mockitoguy | train |
mockito/mockito/533_557 | mockito/mockito | mockito/mockito/533 | mockito/mockito/557 | [
"keyword_pr_to_issue",
"timestamp(timedelta=0.0, similarity=0.8874129473043729)"
] | 4ce9ac2ea38153f4f0c7e272d52fdf9a494ccb14 | a8c9b1c9a40a3702979b6feace16e1acd6349281 | [] | [] | "2016-08-15T15:30:34Z" | [
"docs"
] | Remove code.google.com from javadoc | Looks like the javadoc still has some references to code.google.com, let's replace them with up to date links.
| [
".github/CONTRIBUTING.md",
"src/main/java/org/mockito/AdditionalAnswers.java",
"src/main/java/org/mockito/MockSettings.java",
"src/main/java/org/mockito/Mockito.java"
] | [
".github/CONTRIBUTING.md",
"src/main/java/org/mockito/AdditionalAnswers.java",
"src/main/java/org/mockito/MockSettings.java",
"src/main/java/org/mockito/Mockito.java"
] | [] | diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md
index ebab07f5f0..1fe4857285 100644
--- a/.github/CONTRIBUTING.md
+++ b/.github/CONTRIBUTING.md
@@ -27,7 +27,7 @@
* Also, don't hesitate to ask questions on the [mailing list](https://groups.google.com/forum/#!forum/mockito) - that helps us improve javadocs/FAQ.
* Please suggest changes to javadoc/exception messages when you find something unclear.
* If you miss a particular feature in Mockito - browse or ask on the mailing list, show us a sample code and describe the problem.
-* Wondering what to work on? See [task/bug list](https://github.com/mockito/mockito/issues/) [(old task/bug list)](http://code.google.com/p/mockito/issues/list) and pick up something you would like to work on. Remember that some feature requests we somewhat not agree with so not everything we want to work on :)
+* Wondering what to work on? See [task/bug list](https://github.com/mockito/mockito/issues/) and pick up something you would like to work on. Remember that some feature requests we somewhat not agree with so not everything we want to work on :)
* Mockito currently uses GitHub for versioning so you can *create a fork of Mockito in no time*. Go to the [github project](https://github.com/mockito/mockito) and "Create your own fork". Create a new branch, commit, ..., when you're ready let us know about your pull request so we can discuss it and merge the PR!
* Note the project now uses *gradle*, when your Gradle install is ready, make your IDE project's files (for example **`gradle idea`**). Other gradle commands are listed via **`gradle tasks`**.
@@ -38,18 +38,18 @@ For that reason each pull request has to go through a thorough review and/or dis
Things we pay attention in a PR :
-* On pull requests, please document the change, what it brings, what is the benefit. If the issue exists on the old issue tracker on [Google Code](https://code.google.com/p/mockito/issues/list), please add cross links. But don't create a new one there.
+* On pull requests, please document the change, what it brings, what is the benefit.
* **Clean commit history** in the topic branch in your fork of the repository, even during review. That means that commits are _rebased_ and _squashed_ if necessary, so that each commit clearly changes one things and there are no extraneous fix-ups.
For that matter it's possible to commit [_semantic_ changes](http://lemike-de.tumblr.com/post/79041908218/semantic-commits). _Tests are an asset, so is history_.
-
+
_Exemple gratia_:
-
+
```
Fixes #73 : The new feature
Fixes #73 : Refactors this part of Mockito to make feature possible
```
-
+
* In the code, always test your feature / change, in unit tests and in our `acceptance test suite` located in `org.mockitousage`. Older tests will be migrated when a test is modified.
* New test methods should follow a snake case convention (`ensure_that_stuff_is_doing_that`), this allows the test name to be fully expressive on intent while still readable.
* When reporting errors to the users, if it's a user report report it gently and explain how a user should deal with it, see the `Reporter` class. However not all errors should go there, some unlikely technical errors don't need to be in the `Reporter` class.
@@ -58,4 +58,3 @@ Things we pay attention in a PR :
_If you are unsure about git you can have a look on our [git tips to have a clean history](https://github.com/mockito/mockito/wiki/Using git to prepare your PR to have a clean history)._
-
diff --git a/src/main/java/org/mockito/AdditionalAnswers.java b/src/main/java/org/mockito/AdditionalAnswers.java
index fd97305ef2..9ee4a20013 100644
--- a/src/main/java/org/mockito/AdditionalAnswers.java
+++ b/src/main/java/org/mockito/AdditionalAnswers.java
@@ -122,8 +122,7 @@ public static <T> Answer<T> returnsArgAt(int position) {
* <li>Already custom proxied object</li>
* <li>Special objects with a finalize method, i.e. to avoid executing it 2 times</li>
* </ul>
- * For more details including the use cases reported by users take a look at
- * <a link="http://code.google.com/p/mockito/issues/detail?id=145">issue 145</a>.
+ *
* <p>
* The difference with the regular spy:
* <ul>
diff --git a/src/main/java/org/mockito/MockSettings.java b/src/main/java/org/mockito/MockSettings.java
index 2b5f934694..137764c35f 100644
--- a/src/main/java/org/mockito/MockSettings.java
+++ b/src/main/java/org/mockito/MockSettings.java
@@ -40,7 +40,6 @@ public interface MockSettings extends Serializable {
/**
* Specifies extra interfaces the mock should implement. Might be useful for legacy code or some corner cases.
- * For background, see issue 51 <a href="http://code.google.com/p/mockito/issues/detail?id=51">here</a>
* <p>
* This mysterious feature should be used very occasionally.
* The object under test should know exactly its collaborators & dependencies.
diff --git a/src/main/java/org/mockito/Mockito.java b/src/main/java/org/mockito/Mockito.java
index ec953791d2..f92ff50d51 100644
--- a/src/main/java/org/mockito/Mockito.java
+++ b/src/main/java/org/mockito/Mockito.java
@@ -674,8 +674,7 @@
* <p>
* The only reason we added <code>reset()</code> method is to
* make it possible to work with container-injected mocks.
- * See issue 55 (<a href="http://code.google.com/p/mockito/issues/detail?id=55">here</a>)
- * or FAQ (<a href="http://code.google.com/p/mockito/wiki/FAQ">here</a>).
+ * For more information see FAQ (<a href="https://github.com/mockito/mockito/wiki/FAQ">here</a>).
* <p>
* <b>Don't harm yourself.</b> <code>reset()</code> in the middle of the test method is a code smell (you're probably testing too much).
* <pre class="code"><code class="java">
@@ -693,7 +692,7 @@
* <h3 id="18">18. <a class="meaningful_link" href="#framework_validation">Troubleshooting & validating framework usage</a> (Since 1.8.0)</h3>
*
* First of all, in case of any trouble, I encourage you to read the Mockito FAQ:
- * <a href="http://code.google.com/p/mockito/wiki/FAQ">http://code.google.com/p/mockito/wiki/FAQ</a>
+ * <a href="https://github.com/mockito/mockito/wiki/FAQ">https://github.com/mockito/mockito/wiki/FAQ</a>
* <p>
* In case of questions you may also post to mockito mailing list:
* <a href="http://groups.google.com/group/mockito">http://groups.google.com/group/mockito</a>
@@ -1812,8 +1811,7 @@ public static <T> T verify(T mock, VerificationMode mode) {
* <p>
* The only reason we added <code>reset()</code> method is to
* make it possible to work with container-injected mocks.
- * See issue 55 (<a href="http://code.google.com/p/mockito/issues/detail?id=55">here</a>)
- * or FAQ (<a href="http://code.google.com/p/mockito/wiki/FAQ">here</a>).
+ * For more information see the FAQ (<a href="https://github.com/mockito/mockito/wiki/FAQ">here</a>).
* <p>
* <b>Don't harm yourself.</b> <code>reset()</code> in the middle of the test method is a code smell (you're probably testing too much).
* <pre class="code"><code class="java">
@@ -2202,8 +2200,8 @@ public static Stubber doReturn(Object toBeReturned, Object... toBeReturnedNext)
* Also, you can create InOrder object passing only mocks that are relevant for in-order verification.
* <p>
* <code>InOrder</code> verification is 'greedy', but you will hardly ever notice it.
- * If you want to find out more, search for 'greedy' in the Mockito
- * <a href="http://code.google.com/p/mockito/w/list">wiki pages</a>.
+ * If you want to find out more, read
+ * <a href="https://github.com/mockito/mockito/wiki/Greedy-algorithm-of-verfication-InOrder">this wiki page</a>.
* <p>
* As of Mockito 1.8.4 you can verifyNoMoreInvocations() in order-sensitive way. Read more: {@link InOrder#verifyNoMoreInteractions()}
* <p>
@@ -2485,7 +2483,7 @@ public static VerificationAfterDelay after(long millis) {
}
/**
- * First of all, in case of any trouble, I encourage you to read the Mockito FAQ: <a href="http://code.google.com/p/mockito/wiki/FAQ">http://code.google.com/p/mockito/wiki/FAQ</a>
+ * First of all, in case of any trouble, I encourage you to read the Mockito FAQ: <a href="https://github.com/mockito/mockito/wiki/FAQ">https://github.com/mockito/mockito/wiki/FAQ</a>
* <p>
* In case of questions you may also post to mockito mailing list: <a href="http://groups.google.com/group/mockito">http://groups.google.com/group/mockito</a>
* <p>
| null | val | train | 2016-08-15T15:27:39 | "2016-08-05T21:12:20Z" | bric3 | train |
mockito/mockito/554_560 | mockito/mockito | mockito/mockito/554 | mockito/mockito/560 | [
"timestamp(timedelta=1.0, similarity=0.8625271174305021)",
"keyword_pr_to_issue"
] | d5fec63dd1268fae0cdd91e3e8f760e4b806af55 | 38610245f27225fb7ce1b50dd355bd7b0ac86792 | [
"Definitely! Personally I hate throwing NPEs. NPE can be thrown because you've forgotten to inject sth and your test (if you test for an NPE exception to be thrown) will pass.\n",
"Agreed \n"
] | [] | "2016-08-16T10:18:25Z" | [
"enhancement"
] | Checks.checkNotNull should emit IllegalArgumentException instead of NPE | Checks.checkNotNull emits NPE. I think it is better to emit IAE, because:
- IAE is more specific whereas NPE is more generic. Specific exception is easier to test.
- Specific exception gives better experience for users, NPE is often assumed to be developer error.
This change is not backwards compatible.
@bric3, thoughts?
| [
"src/main/java/org/mockito/internal/util/Checks.java"
] | [
"src/main/java/org/mockito/internal/util/Checks.java"
] | [
"src/test/java/org/mockito/internal/configuration/MockInjectionTest.java"
] | diff --git a/src/main/java/org/mockito/internal/util/Checks.java b/src/main/java/org/mockito/internal/util/Checks.java
index 00ed8a8f22..acb8e914b0 100644
--- a/src/main/java/org/mockito/internal/util/Checks.java
+++ b/src/main/java/org/mockito/internal/util/Checks.java
@@ -12,7 +12,7 @@ public class Checks {
public static <T> T checkNotNull(T value, String checkedValue) {
if(value == null) {
- throw new NullPointerException(checkedValue + " should not be null");
+ throw new IllegalArgumentException(checkedValue + " should not be null");
}
return value;
}
| diff --git a/src/test/java/org/mockito/internal/configuration/MockInjectionTest.java b/src/test/java/org/mockito/internal/configuration/MockInjectionTest.java
index ed20c9ccc2..4abb528042 100644
--- a/src/test/java/org/mockito/internal/configuration/MockInjectionTest.java
+++ b/src/test/java/org/mockito/internal/configuration/MockInjectionTest.java
@@ -29,22 +29,22 @@ public void reset() throws Exception {
withoutConstructor = null;
}
- @Test(expected = NullPointerException.class)
+ @Test(expected = IllegalArgumentException.class)
public void should_not_allow_null_on_field() {
MockInjection.onField((Field) null, this);
}
- @Test(expected = NullPointerException.class)
+ @Test(expected = IllegalArgumentException.class)
public void should_not_allow_null_on_fields() {
MockInjection.onFields((Set<Field>) null, this);
}
- @Test(expected = NullPointerException.class)
+ @Test(expected = IllegalArgumentException.class)
public void should_not_allow_null_on_instance_owning_the_field() throws Exception {
MockInjection.onField(field("withConstructor"), null);
}
- @Test(expected = NullPointerException.class)
+ @Test(expected = IllegalArgumentException.class)
public void should_not_allow_null_on_mocks() throws Exception {
MockInjection.onField(field("withConstructor"), this).withMocks(null);
}
| test | train | 2016-08-16T10:27:07 | "2016-08-14T18:08:05Z" | mockitoguy | train |
mockito/mockito/541_569 | mockito/mockito | mockito/mockito/541 | mockito/mockito/569 | [
"timestamp(timedelta=0.0, similarity=0.9188712415398987)"
] | e38764fa0c5fb0373b8a82120b12a2b635e363a9 | 18d421778e1952f8e8f291201207702ac590edc9 | [
"OK but let's deprecate them instead of removing them (possibly in mockito 3).\n",
"Given that getMockedType() and getExtraInterfaces() are unreleased yet (e.g. 2.0), do you still opt for deprecation?\n",
"good point, let's remove them then !\n"
] | [
"I think the assertions should be on the constructor. This enable a fail fast behavior.\n",
"We cannot have them on constructor at the moment because isMock / isSpy methods permit null / non-mock arguments. Options:\n1. separate isMock / isSpy API somewhere else\n2. return empty / null result from getInvocations / getCreationSettings - then we don't need any exception\n3. leave things as they are (merge PR :D)\n4. ?\n\nMy thinking process\n\n1 - API discoverability suffers\n2 - poor API, no distinction between non-mock and mock without invocations, null handling required for the client code\n3 - late exception not ideal but acceptable IMO\n\nGood feedback!\n",
"> We cannot have them on constructor at the moment because isMock / isSpy methods permit null / non-mock arguments. \n\nGood point. That was a suggestion only. But that work too !\n\nDiscoverability won't suffer that much. Imho\n",
"@szczepiq We should use the ExpectedException Rule here. WDYT?\n",
"@ChristianSchwarz I'm not a fan of `ExpectedException` rule, this make the test a bit awkward, try/catch is a bit more bulky but it offers more control.\n\nAlso when we switch to Java8 after mockito 2, we can bump to AssertJ 3.x which has interesting assertions like : \n\n``` java\nAssertions.assertThatThrownBy(() -> mockingDetails(null).getInvocations())\n .isInstanceOf(NotAMockException.class)\n .hasMessageContaining(\"Argument passed to Mockito.mockingDetails() should be a mock, but is null!\")\n```\n"
] | "2016-08-19T23:13:16Z" | [
"enhancement"
] | improve Mockito.mockingDetails API | In order to make the API cleaner & expose useful information:
1. MockingDetails.getInvocations() throws meaningful exception when passed object is not a mock and documents this behavior
2. getMockedType() and getExtraInterfaces() are replaced with getMockCreationSettings() that returns MockCreationSettings instance.
| [
"src/main/java/org/mockito/MockingDetails.java",
"src/main/java/org/mockito/internal/util/DefaultMockingDetails.java"
] | [
"src/main/java/org/mockito/MockingDetails.java",
"src/main/java/org/mockito/internal/util/DefaultMockingDetails.java"
] | [
"src/test/java/org/mockito/internal/util/DefaultMockingDetailsTest.java"
] | diff --git a/src/main/java/org/mockito/MockingDetails.java b/src/main/java/org/mockito/MockingDetails.java
index ee8496380e..534cbd02f8 100644
--- a/src/main/java/org/mockito/MockingDetails.java
+++ b/src/main/java/org/mockito/MockingDetails.java
@@ -5,9 +5,9 @@
package org.mockito;
import org.mockito.invocation.Invocation;
+import org.mockito.mock.MockCreationSettings;
import java.util.Collection;
-import java.util.Set;
/**
* Provides mocking information.
@@ -36,27 +36,24 @@ public interface MockingDetails {
/**
* All method invocations on this mock.
* Can be empty - it means there were no interactions with the mock.
+ * <p>
+ * This method is useful for framework integrators and for certain edge cases.
*
* @since 1.10.0
*/
Collection<Invocation> getInvocations();
/**
- * Returns the type that is mocked. It is the type originally passed to
- * the <code>{@link Mockito#mock(Class)}</code> or <code>{@link Mockito#spy(Class)}</code> function,
- * or the type referenced by a Mockito annotation.
- *
- * @return The mocked type
- * @since 2.0.0
- */
- Class<?> getMockedType();
-
- /**
- * Returns the extra-interfaces of the mock. The interfaces that were configured at the mock creation
- * with the <code>{@link MockSettings#extraInterfaces(Class[])}</code>.
- *
- * @return The extra-interfaces
+ * Returns various mock settings provided when the mock was created, for example:
+ * mocked class, mock name (if any), any extra interfaces (if any), etc.
+ * See also {@link MockCreationSettings}.
+ * <p>
+ * This method is useful for framework integrators and for certain edge cases.
+ * <p>
+ * If <code>null</code> or non-mock was passed to {@link Mockito#mockingDetails(Object)}
+ * then this method will throw with an appropriate exception.
+ * After all, non-mock objects do not have any mock creation settings.
* @since 2.0.0
*/
- Set<Class<?>> getExtraInterfaces();
+ MockCreationSettings<?> getMockCreationSettings();
}
diff --git a/src/main/java/org/mockito/internal/util/DefaultMockingDetails.java b/src/main/java/org/mockito/internal/util/DefaultMockingDetails.java
index f7a91dfbba..5117ccbf96 100644
--- a/src/main/java/org/mockito/internal/util/DefaultMockingDetails.java
+++ b/src/main/java/org/mockito/internal/util/DefaultMockingDetails.java
@@ -5,12 +5,14 @@
package org.mockito.internal.util;
import org.mockito.MockingDetails;
+import org.mockito.exceptions.misusing.NotAMockException;
+import org.mockito.internal.InternalMockHandler;
import org.mockito.invocation.Invocation;
-
-import static org.mockito.internal.util.MockUtil.getMockHandler;
+import org.mockito.mock.MockCreationSettings;
import java.util.Collection;
-import java.util.Set;
+
+import static org.mockito.internal.util.MockUtil.getMockHandler;
/**
* Class to inspect any object, and identify whether a particular object is either a mock or a spy. This is
@@ -36,17 +38,25 @@ public boolean isSpy(){
@Override
public Collection<Invocation> getInvocations() {
- return getMockHandler(toInspect).getInvocationContainer().getInvocations();
+ return mockHandler().getInvocationContainer().getInvocations();
}
@Override
- public Class<?> getMockedType() {
- return getMockHandler(toInspect).getMockSettings().getTypeToMock();
+ public MockCreationSettings<?> getMockCreationSettings() {
+ return mockHandler().getMockSettings();
}
- @Override
- public Set<Class<?>> getExtraInterfaces() {
- return getMockHandler(toInspect).getMockSettings().getExtraInterfaces();
+ private InternalMockHandler<Object> mockHandler() {
+ assertGoodMock();
+ return getMockHandler(toInspect);
+ }
+
+ private void assertGoodMock() {
+ if (toInspect == null) {
+ throw new NotAMockException("Argument passed to Mockito.mockingDetails() should be a mock, but is null!");
+ } else if (!isMock()) {
+ throw new NotAMockException("Argument passed to Mockito.mockingDetails() should be a mock, but is an instance of " + toInspect.getClass() + "!");
+ }
}
}
| diff --git a/src/test/java/org/mockito/MockingDetailsTest.java b/src/test/java/org/mockito/MockingDetailsTest.java
deleted file mode 100644
index ba870517a3..0000000000
--- a/src/test/java/org/mockito/MockingDetailsTest.java
+++ /dev/null
@@ -1,51 +0,0 @@
-package org.mockito;
-
-import org.junit.Test;
-import org.mockito.internal.MockitoCore;
-import org.mockito.invocation.Invocation;
-import org.mockitoutil.TestBase;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-
-import static junit.framework.TestCase.*;
-import static org.mockito.Mockito.mock;
-
-public class MockingDetailsTest extends TestBase {
-
- @Test
- public void should_provide_invocations() {
- List<String> methodsInvoked = new ArrayList<String>() {{
- add("add");
- add("remove");
- add("clear");
- }};
-
- @SuppressWarnings("unchecked")
- List<String> mockedList = (List<String>) mock(List.class);
-
- mockedList.add("one");
- mockedList.remove(0);
- mockedList.clear();
-
- MockingDetails mockingDetails = new MockitoCore().mockingDetails(mockedList);
- Collection<Invocation> invocations = mockingDetails.getInvocations();
-
- assertNotNull(invocations);
- assertEquals(invocations.size(),3);
- for (Invocation method : invocations) {
- assertTrue(methodsInvoked.contains(method.getMethod().getName()));
- if (method.getMethod().getName().equals("add")) {
- assertEquals(method.getArguments().length,1);
- assertEquals(method.getArguments()[0],"one");
- }
- }
- }
-
- @Test
- public void should_handle_null_input() {
- //TODO 541, decide how to handle it and ensure the there is a top level integ test for the mockingDetails().getInvocations()
- //assertTrue(new MockitoCore().mockingDetails(null).getInvocations().isEmpty());
- }
-}
diff --git a/src/test/java/org/mockito/internal/util/DefaultMockingDetailsTest.java b/src/test/java/org/mockito/internal/util/DefaultMockingDetailsTest.java
index 3c151a96f5..225f1a0b48 100644
--- a/src/test/java/org/mockito/internal/util/DefaultMockingDetailsTest.java
+++ b/src/test/java/org/mockito/internal/util/DefaultMockingDetailsTest.java
@@ -1,16 +1,17 @@
package org.mockito.internal.util;
+import junit.framework.TestCase;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.exceptions.misusing.NotAMockException;
import org.mockito.runners.MockitoJUnitRunner;
+import org.mockitousage.IMethods;
-import java.util.*;
-
+import static junit.framework.TestCase.fail;
import static org.junit.Assert.assertEquals;
-import static org.mockito.Mockito.*;
+import static org.mockito.Mockito.mockingDetails;
@SuppressWarnings("unchecked")
@RunWith(MockitoJUnitRunner.class)
@@ -18,6 +19,7 @@ public class DefaultMockingDetailsTest {
@Mock private Foo foo;
@Mock private Bar bar;
+ @Mock private IMethods mock;
@Spy private Gork gork;
@Test
@@ -42,28 +44,51 @@ public void should_check_that_a_spy_is_also_a_mock() throws Exception {
}
@Test
- public void should_get_mocked_type() throws Exception {
- assertEquals(Bar.class, mockingDetails(bar).getMockedType());
- }
+ public void provides_invocations() {
+ //when
+ mock.simpleMethod(10);
+ mock.otherMethod();
- @Test(expected = NotAMockException.class)
- public void should_report_when_not_a_mockito_mock_on_getMockedType() throws Exception {
- mockingDetails("not a mock").getMockedType();
+ //then
+ assertEquals(0, mockingDetails(foo).getInvocations().size());
+ assertEquals("[mock.simpleMethod(10);, mock.otherMethod();]", mockingDetails(mock).getInvocations().toString());
}
@Test
- public void should_get_extra_interfaces() throws Exception {
- Bar loup = mock(Bar.class, withSettings().extraInterfaces(List.class, Observer.class));
- assertEquals(setOf(Observer.class, List.class), mockingDetails(loup).getExtraInterfaces());
+ public void provides_mock_creation_settings() {
+ //smoke test some creation settings
+ assertEquals(Foo.class, mockingDetails(foo).getMockCreationSettings().getTypeToMock());
+ assertEquals(Bar.class, mockingDetails(bar).getMockCreationSettings().getTypeToMock());
+ assertEquals(0, mockingDetails(mock).getMockCreationSettings().getExtraInterfaces().size());
}
@Test(expected = NotAMockException.class)
- public void should_report_when_not_a_mockito_mock_on_getExtraInterfaces() throws Exception {
- mockingDetails("not a mock").getExtraInterfaces();
+ public void fails_when_getting_creation_settings_for_incorrect_input() {
+ mockingDetails(null).getMockCreationSettings();
}
- private <T> Set<T> setOf(T... items) {
- return new HashSet<T>(Arrays.asList(items));
+ @Test
+ public void fails_when_getting_invocations_when_null() {
+ try {
+ //when
+ mockingDetails(null).getInvocations();
+ //then
+ fail();
+ } catch (NotAMockException e) {
+ TestCase.assertEquals("Argument passed to Mockito.mockingDetails() should be a mock, but is null!", e.getMessage());
+ }
+ }
+
+ @Test
+ public void fails_when_getting_invocations_when_not_mock() {
+ try {
+ //when
+ mockingDetails(new Object()).getInvocations();
+ //then
+ fail();
+ } catch (NotAMockException e) {
+ TestCase.assertEquals("Argument passed to Mockito.mockingDetails() should be a mock, but is an instance of class java.lang.Object!", e.getMessage());
+ }
}
public class Foo { }
| train | train | 2016-08-17T12:02:24 | "2016-08-10T00:38:47Z" | mockitoguy | train |
mockito/mockito/570_571 | mockito/mockito | mockito/mockito/570 | mockito/mockito/571 | [
"keyword_pr_to_issue"
] | 92d71605142dda602d7f6032c187d223695f29d8 | 78214f71330b74fc436fe2f932647df39dbf03a0 | [
"@tokuhirom Thanks for the report\n\nIt seems this issue holds true for older versions of mockito like 1.9.5.\n"
] | [
"Also add an assert for multiple values in a hashmap.\n",
"Probably for multiple values it would be good to add some white-space around the `=` and maybe put them on a new-line.\n",
"Added test case for mutliple values in a hashmap.\n",
"And, added white-spaces around the '='\n",
"@tokuhirom \nfor better readability better use [Collections.singletonMap(K,V)](https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#singletonMap%28K,%20V%29) here \n"
] | "2016-08-20T02:31:50Z" | [
"enhancement"
] | Hard to understand argument difference between int and long | check that
- [x] The mockito message in the stacktrace have useful information, but it didn't help
- [x] The problematic code (if that's possible) is copied here;
Note that some configuration are impossible to mock via Mockito
- [x] Provide versions (mockito / jdk / os / any other relevant information)
- [x] Provide a [Short, Self Contained, Correct (Compilable), Example](http://sscce.org) of the issue
(same as any question on stackoverflow.com)
- [x] Read the [contributing guide](https://github.com/mockito/mockito/blob/master/.github/CONTRIBUTING.md)
JDK: 1.8
OS: linux
mockito: master branch
Sample code:
```
package com.example;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.runners.MockitoJUnitRunner;
import java.util.HashMap;
import java.util.Map;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
public class HogeTest {
@Test
public void test() {
Hello hello = mock(Hello.class);
hello.greeting(new HashMap<String, Object>() {{
put("hello", 3L);
}});
verify(hello).greeting(new HashMap<String, Object>() {{
put("hello", 3);
}});
}
public static class Hello {
void greeting(Map<String, Object> l) {
}
}
}
```
Output:
```
Testing started at 8:37 AM ...
8:37:01 AM: Executing external tasks ':cleanTest :test --tests "com.example.HogeTest.test"'...
:cleanTest
:compileJava UP-TO-DATE
:processResources UP-TO-DATE
:classes UP-TO-DATE
:compileTestJava
:processTestResources UP-TO-DATE
:testClasses
:test
com.example.HogeTest > test FAILED
org.mockito.exceptions.verification.junit.ArgumentsAreDifferent at HogeTest.java:31
Argument(s) are different! Wanted:
hello.greeting(() {hello=3});
-> at com.example.HogeTest.test(HogeTest.java:31)
Actual invocation has different arguments:
hello.greeting(() {hello=3});
-> at com.example.HogeTest.test(HogeTest.java:26)
Argument(s) are different! Wanted:
hello.greeting(() {hello=3});
-> at com.example.HogeTest.test(HogeTest.java:31)
Actual invocation has different arguments:
hello.greeting(() {hello=3});
-> at com.example.HogeTest.test(HogeTest.java:26)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at com.example.HogeTest.test(HogeTest.java:31)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37)
at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.runTestClass(JUnitTestClassExecuter.java:105)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.execute(JUnitTestClassExecuter.java:56)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassProcessor.processTestClass(JUnitTestClassProcessor.java:64)
at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:50)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
at org.gradle.messaging.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:32)
at org.gradle.messaging.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93)
at com.sun.proxy.$Proxy2.processTestClass(Unknown Source)
at org.gradle.api.internal.tasks.testing.worker.TestWorker.processTestClass(TestWorker.java:106)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
at org.gradle.messaging.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:360)
at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:54)
at org.gradle.internal.concurrent.StoppableExecutorImpl$1.run(StoppableExecutorImpl.java:40)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
1 test completed, 1 failed
:test FAILED
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':test'.
> There were failing tests. See the report at: file:///Users/tokuhirom/dev/mockito-sample/build/reports/tests/index.html
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
BUILD FAILED
Total time: 1.713 secs
There were failing tests. See the report at: file:///Users/tokuhirom/dev/mockito-sample/build/reports/tests/index.html
```
In this case, user can't understand the difference between _wanted_ and _actual_. Since 2 dumps are same!
```
Argument(s) are different! Wanted:
hello.greeting(() {hello=3});
-> at com.example.HogeTest.test(HogeTest.java:31)
Actual invocation has different arguments:
hello.greeting(() {hello=3});
-> at com.example.HogeTest.test(HogeTest.java:26)
```
If there's a _L_ suffix for long value, user can understand the difference.
| [
"src/main/java/org/mockito/internal/matchers/text/ValuePrinter.java"
] | [
"src/main/java/org/mockito/internal/matchers/text/ValuePrinter.java"
] | [
"src/test/java/org/mockito/internal/matchers/EqualsTest.java",
"src/test/java/org/mockito/internal/matchers/MatchersPrinterTest.java",
"src/test/java/org/mockito/internal/matchers/text/ValuePrinterTest.java",
"src/test/java/org/mockitousage/verification/DescriptiveMessagesWhenVerificationFailsTest.java",
"src/test/java/org/mockitousage/verification/PrintingVerboseTypesWithArgumentsTest.java"
] | diff --git a/src/main/java/org/mockito/internal/matchers/text/ValuePrinter.java b/src/main/java/org/mockito/internal/matchers/text/ValuePrinter.java
index f382c39ffb..10575d3ae1 100644
--- a/src/main/java/org/mockito/internal/matchers/text/ValuePrinter.java
+++ b/src/main/java/org/mockito/internal/matchers/text/ValuePrinter.java
@@ -1,6 +1,7 @@
package org.mockito.internal.matchers.text;
import java.util.Iterator;
+import java.util.Map;
import static java.lang.String.valueOf;
@@ -21,6 +22,16 @@ public static String print(Object value) {
return "\"" + value + "\"";
} else if (value instanceof Character) {
return printChar((Character) value);
+ } else if (value instanceof Long) {
+ return value + "L";
+ } else if (value instanceof Double) {
+ return value + "d";
+ } else if (value instanceof Float) {
+ return value + "f";
+ } else if (value instanceof Byte) {
+ return String.format("0x%02X", (Byte) value);
+ } else if (value instanceof Map) {
+ return printMap((Map) value);
} else if (value.getClass().isArray()) {
return printValues("[", ", ", "]", new org.mockito.internal.matchers.text.ArrayIterator(value));
} else if (value instanceof FormattedText) {
@@ -30,6 +41,19 @@ public static String print(Object value) {
return descriptionOf(value);
}
+ private static String printMap(Map<?,?> map) {
+ StringBuilder result = new StringBuilder();
+ Iterator<? extends Map.Entry<?, ?>> iterator = map.entrySet().iterator();
+ while (iterator.hasNext()) {
+ Map.Entry<?, ?> entry = iterator.next();
+ result.append(print(entry.getKey())).append(" = ").append(print(entry.getValue()));
+ if (iterator.hasNext()) {
+ result.append(", ");
+ }
+ }
+ return "{" + result.toString() + "}";
+ }
+
/**
* Print values in a nice format, e.g. (1, 2, 3)
*
| diff --git a/src/test/java/org/mockito/internal/matchers/EqualsTest.java b/src/test/java/org/mockito/internal/matchers/EqualsTest.java
index d0d92d6a75..6664f68bb7 100644
--- a/src/test/java/org/mockito/internal/matchers/EqualsTest.java
+++ b/src/test/java/org/mockito/internal/matchers/EqualsTest.java
@@ -39,7 +39,7 @@ public void shouldDescribeWithExtraTypeInfo() throws Exception {
public void shouldDescribeWithExtraTypeInfoOfLong() throws Exception {
String descStr = new Equals(100L).toStringWithType();
- assertEquals("(Long) 100", descStr);
+ assertEquals("(Long) 100L", descStr);
}
@Test
diff --git a/src/test/java/org/mockito/internal/matchers/MatchersPrinterTest.java b/src/test/java/org/mockito/internal/matchers/MatchersPrinterTest.java
index efbf377621..eaeea5ec5e 100644
--- a/src/test/java/org/mockito/internal/matchers/MatchersPrinterTest.java
+++ b/src/test/java/org/mockito/internal/matchers/MatchersPrinterTest.java
@@ -36,7 +36,7 @@ public void shouldDescribeTypeInfoOnlyMarkedMatchers() {
//when
String line = printer.getArgumentsLine((List) Arrays.asList(new Equals(1L), new Equals(2)), PrintSettings.verboseMatchers(1));
//then
- assertEquals("(1, (Integer) 2);", line);
+ assertEquals("(1L, (Integer) 2);", line);
}
@Test
@@ -44,7 +44,7 @@ public void shouldDescribeStringMatcher() {
//when
String line = printer.getArgumentsLine((List) Arrays.asList(new Equals(1L), new Equals("x")), PrintSettings.verboseMatchers(1));
//then
- assertEquals("(1, (String) \"x\");", line);
+ assertEquals("(1L, (String) \"x\");", line);
}
@Test
@@ -52,7 +52,7 @@ public void shouldGetVerboseArgumentsInBlock() {
//when
String line = printer.getArgumentsBlock((List) Arrays.asList(new Equals(1L), new Equals(2)), PrintSettings.verboseMatchers(0, 1));
//then
- assertEquals("(\n (Long) 1,\n (Integer) 2\n);", line);
+ assertEquals("(\n (Long) 1L,\n (Integer) 2\n);", line);
}
@Test
@@ -60,6 +60,6 @@ public void shouldGetVerboseArgumentsEvenIfSomeMatchersAreNotVerbose() {
//when
String line = printer.getArgumentsLine((List) Arrays.asList(new Equals(1L), NotNull.NOT_NULL), PrintSettings.verboseMatchers(0));
//then
- assertEquals("((Long) 1, notNull());", line);
+ assertEquals("((Long) 1L, notNull());", line);
}
}
\ No newline at end of file
diff --git a/src/test/java/org/mockito/internal/matchers/text/ValuePrinterTest.java b/src/test/java/org/mockito/internal/matchers/text/ValuePrinterTest.java
index 1ecc8cfb3e..ac7235b345 100644
--- a/src/test/java/org/mockito/internal/matchers/text/ValuePrinterTest.java
+++ b/src/test/java/org/mockito/internal/matchers/text/ValuePrinterTest.java
@@ -3,6 +3,8 @@
import org.junit.Test;
+import java.util.LinkedHashMap;
+
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.internal.matchers.text.ValuePrinter.print;
@@ -14,7 +16,26 @@ public void prints_values() throws Exception {
assertEquals("null", print(null));
assertEquals("\"str\"", print("str"));
assertEquals("\"x\ny\"", print("x\ny"));
+ assertEquals("3", print(3));
+ assertEquals("3L", print(3L));
+ assertEquals("3.14d", print(3.14d));
+ assertEquals("3.14f", print(3.14f));
assertEquals("[1, 2]", print(new int[]{1, 2}));
+ assertEquals("{\"foo\" = 2L}", print(new LinkedHashMap<String, Object>() {
+ {
+ put("foo", 2L);
+ }
+ }));
+ assertEquals("{\"byte\" = 0x01, \"short\" = 2, \"int\" = 3, \"long\" = 4L, \"float\" = 2.71f, \"double\" = 3.14d}", print(new LinkedHashMap<String, Object>() {
+ {
+ put("byte", (byte)1);
+ put("short", (short)2);
+ put("int", 3);
+ put("long", 4L);
+ put("float", 2.71f);
+ put("double", 3.14d);
+ }
+ }));
assertTrue(print(new UnsafeToString()).contains("UnsafeToString"));
assertEquals("ToString", print(new ToString()));
assertEquals("formatted", print(new FormattedText("formatted")));
diff --git a/src/test/java/org/mockitousage/verification/DescriptiveMessagesWhenVerificationFailsTest.java b/src/test/java/org/mockitousage/verification/DescriptiveMessagesWhenVerificationFailsTest.java
index 1a2a10cde4..c75b6b05d3 100644
--- a/src/test/java/org/mockitousage/verification/DescriptiveMessagesWhenVerificationFailsTest.java
+++ b/src/test/java/org/mockitousage/verification/DescriptiveMessagesWhenVerificationFailsTest.java
@@ -374,7 +374,7 @@ public void should_print_method_name_and_arguments_of_other_interactions_with_di
assertThat(e)
.hasMessageContaining("iMethods.threeArgumentMethod(12, foo, \"xx\")")
.hasMessageContaining("iMethods.arrayMethod([\"a\", \"b\", \"c\"])")
- .hasMessageContaining("iMethods.forByte(25)");
+ .hasMessageContaining("iMethods.forByte(0x19)");
}
}
diff --git a/src/test/java/org/mockitousage/verification/PrintingVerboseTypesWithArgumentsTest.java b/src/test/java/org/mockitousage/verification/PrintingVerboseTypesWithArgumentsTest.java
index 233ea4dabb..2c44d9bb44 100644
--- a/src/test/java/org/mockitousage/verification/PrintingVerboseTypesWithArgumentsTest.java
+++ b/src/test/java/org/mockitousage/verification/PrintingVerboseTypesWithArgumentsTest.java
@@ -42,7 +42,7 @@ public void should_not_report_argument_types_when_to_string_is_the_same() {
//then
assertThat(e)
.hasMessageContaining("withLong((Integer) 100);")
- .hasMessageContaining("withLong((Long) 100);");
+ .hasMessageContaining("withLong((Long) 100L);");
}
}
@@ -60,7 +60,7 @@ public void should_show_the_type_of_only_the_argument_that_doesnt_match() {
//then
assertThat(e)
.hasMessageContaining("withLongAndInt((Integer) 100, 200)")
- .hasMessageContaining("withLongAndInt((Long) 100, 200)");
+ .hasMessageContaining("withLongAndInt((Long) 100L, 200)");
}
}
@@ -78,7 +78,7 @@ public void should_show_the_type_of_the_mismatching_argument_when_output_descrip
//then
Assertions.assertThat(e.getMessage())
.contains("withLongAndInt(\n" +
- " (Long) 100,\n" +
+ " (Long) 100L,\n" +
" 200\n" +
")")
.contains("withLongAndInt(\n" +
@@ -101,8 +101,8 @@ public void should_not_show_types_when_argument_value_is_different() {
} catch (ArgumentsAreDifferent e) {
//then
assertThat(e)
- .hasMessageContaining("withLongAndInt(100, 200)")
- .hasMessageContaining("withLongAndInt(100, 230)");
+ .hasMessageContaining("withLongAndInt(100L, 200)")
+ .hasMessageContaining("withLongAndInt(100L, 230)");
}
}
| train | train | 2016-08-20T20:06:42 | "2016-08-20T02:30:50Z" | tokuhirom | train |
mockito/mockito/564_576 | mockito/mockito | mockito/mockito/564 | mockito/mockito/576 | [
"timestamp(timedelta=0.0, similarity=0.8430518118731711)",
"keyword_pr_to_issue"
] | cc9f19cceb40c7f9fa66d9495f95d2c4dc2f47f8 | 64be0917781a12f42eeea44f199d7340b5693f73 | [] | [
":joy: \n"
] | "2016-08-20T15:12:54Z" | [] | Publish Mockito build results to Gradle Build Scans | Let's start publishing Mockito build results to Gradle Build Scans. This way we have extra intel about Gradle builds. This also helps friends at Gradle as they will have more projects on board!
| [
".travis.yml",
"build.gradle",
"gradle/wrapper/gradle-wrapper.properties",
"gradlew",
"gradlew.bat",
"src/main/java/org/mockito/internal/junit/StubbingArgMismatches.java",
"src/main/java/org/mockito/internal/junit/UnusedStubbings.java"
] | [
".travis.yml",
"build.gradle",
"gradle/wrapper/gradle-wrapper.properties",
"gradlew",
"gradlew.bat",
"src/main/java/org/mockito/internal/junit/StubbingArgMismatches.java",
"src/main/java/org/mockito/internal/junit/UnusedStubbings.java"
] | [] | diff --git a/.travis.yml b/.travis.yml
index 7ec6b9b61d..46a81e5c81 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -49,7 +49,7 @@ branches:
install:
- true
script:
- - ./gradlew ciBuild release
+ - ./gradlew ciBuild release -Dscan
after_success:
- ./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"
diff --git a/build.gradle b/build.gradle
index 9d40980a89..ea9a70728e 100644
--- a/build.gradle
+++ b/build.gradle
@@ -8,6 +8,11 @@ buildscript {
classpath 'org.codehaus.groovy.modules.http-builder:http-builder:0.5.2' //rest calls to bintray api
}
}
+
+plugins {
+ id 'com.gradle.build-scan' version '1.0'
+}
+
apply plugin: 'java'
group = 'org.mockito'
description = 'Core API and implementation.'
@@ -117,7 +122,7 @@ apply from: 'gradle/release.gradle'
apply from: "gradle/pom.gradle"
task wrapper(type: Wrapper) {
- gradleVersion = '2.4'
+ gradleVersion = '2.14.1'
}
task ciBuild {
@@ -128,3 +133,9 @@ task ciBuild {
//Making sure that release task is only invoked after the entire ciBuild validation
release.mustRunAfter ciBuild
+
+//Posting Build scans to https://scans.gradle.com
+buildScan {
+ licenseAgreementUrl = 'https://gradle.com/terms-of-service'
+ licenseAgree = 'yes'
+}
diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties
index 0b5a32f1e1..69ef29851a 100644
--- a/gradle/wrapper/gradle-wrapper.properties
+++ b/gradle/wrapper/gradle-wrapper.properties
@@ -1,6 +1,6 @@
-#Wed Jul 06 11:31:59 CEST 2016
+#Fri Aug 19 18:41:31 PDT 2016
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
-distributionUrl=https\://services.gradle.org/distributions/gradle-2.11-all.zip
+distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-bin.zip
diff --git a/gradlew b/gradlew
index 91a7e269e1..9d82f78915 100755
--- a/gradlew
+++ b/gradlew
@@ -42,11 +42,6 @@ case "`uname`" in
;;
esac
-# For Cygwin, ensure paths are in UNIX format before anything is touched.
-if $cygwin ; then
- [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
-fi
-
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
@@ -61,9 +56,9 @@ while [ -h "$PRG" ] ; do
fi
done
SAVED="`pwd`"
-cd "`dirname \"$PRG\"`/" >&-
+cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
-cd "$SAVED" >&-
+cd "$SAVED" >/dev/null
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
@@ -114,6 +109,7 @@ fi
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
+ JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
diff --git a/gradlew.bat b/gradlew.bat
index 8a0b282aa6..5f192121eb 100644
--- a/gradlew.bat
+++ b/gradlew.bat
@@ -46,7 +46,7 @@ echo location of your Java installation.
goto fail
:init
-@rem Get command-line arguments, handling Windowz variants
+@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
if "%@eval[2+2]" == "4" goto 4NT_args
diff --git a/src/main/java/org/mockito/internal/junit/StubbingArgMismatches.java b/src/main/java/org/mockito/internal/junit/StubbingArgMismatches.java
index 31a14646a0..53f48b2e2f 100644
--- a/src/main/java/org/mockito/internal/junit/StubbingArgMismatches.java
+++ b/src/main/java/org/mockito/internal/junit/StubbingArgMismatches.java
@@ -27,7 +27,6 @@ public void format(String testName, MockitoLogger logger) {
}
StubbingHint hint = new StubbingHint(testName);
- //TODO 544 it would be nice to make the String look good if x goes multiple digits (padding)
int x = 1;
for (Map.Entry<Invocation, Set<Invocation>> m : mismatches.entrySet()) {
hint.appendLine(x++, ". Unused... ", m.getKey().getLocation());
diff --git a/src/main/java/org/mockito/internal/junit/UnusedStubbings.java b/src/main/java/org/mockito/internal/junit/UnusedStubbings.java
index 1f415ca776..baaf0516ec 100644
--- a/src/main/java/org/mockito/internal/junit/UnusedStubbings.java
+++ b/src/main/java/org/mockito/internal/junit/UnusedStubbings.java
@@ -21,7 +21,6 @@ void format(String testName, MockitoLogger logger) {
return;
}
- //TODO 544 it would be nice to make the String look good if x goes multiple digits (padding)
StubbingHint hint = new StubbingHint(testName);
int x = 1;
for (Stubbing candidate : unused) {
| null | train | train | 2016-08-20T17:03:35 | "2016-08-17T04:17:43Z" | mockitoguy | train |
mockito/mockito/552_589 | mockito/mockito | mockito/mockito/552 | mockito/mockito/589 | [
"keyword_pr_to_issue",
"timestamp(timedelta=1.0, similarity=0.9458023989729777)"
] | 229790dc71e8ef2257c4a74cc7b13d6e6c3dd01f | 8ee3284cf86e8fecd810f564557cd05131c16b62 | [
"Is this as simple as turning back on this line? https://github.com/mockito/mockito/blob/b0393eafeeb81b6c75e40a82b81672543777ca9a/gradle/javadoc.gradle#L55\n",
"Probably but I need to check before. The file may have been removed. And the javadoc tool is _picky_ especially in old version of the JDK.\n",
"Actually we should revert this commit 3a057b3eff2be528a1fed41852a990cff87a72c1, when JDK7 was the only option on travis\n",
"It seems the javadoc tool of openjdk6 generates a different HTML than Sun JDK 6. Thus the stylesheet is not working properly.\n\n<img width=\"748\" alt=\"screen shot 2016-08-24 at 11 56 56\" src=\"https://cloud.githubusercontent.com/assets/803621/17926642/35b9d2cc-69f2-11e6-9614-61648cafeb18.png\">\n\nYet again an issue with OpenJDK6...\n"
] | [] | "2016-08-23T17:52:43Z" | [
"docs"
] | Fix again javadoc stylesheet | Previously we had a nice javadoc stylesheet. That worked well with JDK6.
Then we used travis that was only allowing OracleJDK7, that came with a better javadoc stylesheet so we dropped ours.
Now since the release of mockito 2.x is using openjdk6, we should reintroduce a better stylesheet.
Current state ❌
http://site.mockito.org/mockito/docs/2.0.100-beta/org/mockito/Mockito.html
<img width="712" alt="screen shot 2016-08-13 at 19 41 59" src="https://cloud.githubusercontent.com/assets/803621/17644719/cecc5ec4-618e-11e6-912e-9b0dcd7e94db.png">
Previous ✅
http://site.mockito.org/mockito/docs/2.0.0-beta/org/mockito/Mockito.html
<img width="877" alt="screen shot 2016-08-13 at 19 45 32" src="https://cloud.githubusercontent.com/assets/803621/17644722/d71bcd08-618e-11e6-831a-a01c47e8cc61.png">
| [
"gradle/javadoc.gradle"
] | [
"gradle/javadoc.gradle",
"src/javadoc/stylesheet.css"
] | [] | diff --git a/gradle/javadoc.gradle b/gradle/javadoc.gradle
index 51f4cd4e1d..921589844d 100644
--- a/gradle/javadoc.gradle
+++ b/gradle/javadoc.gradle
@@ -52,7 +52,7 @@ task mockitoJavadoc(type: Javadoc) {
}
</script>
""".replaceAll(/\r|\n/, ""))
-// options.stylesheetFile file("src/javadoc/stylesheet.css")
+ options.stylesheetFile file("src/javadoc/stylesheet.css")
// options.addStringOption('top', 'some html')
if (JavaVersion.current().isJava8Compatible()) {
options.addStringOption('Xdoclint:none', '-quiet')
diff --git a/src/javadoc/stylesheet.css b/src/javadoc/stylesheet.css
new file mode 100644
index 0000000000..f17de4f9fa
--- /dev/null
+++ b/src/javadoc/stylesheet.css
@@ -0,0 +1,63 @@
+/* Javadoc style sheet */
+
+/* Define colors, fonts and other style attributes here to override the defaults */
+
+/* Page background color */
+body { background-color: #FFFFFF; color:#333; font-size: 100%; }
+
+body { font-size: 0.875em; line-height: 1.286em; font-family: "Helvetica", "Arial", sans-serif; }
+
+code { color: #777; line-height: 1.286em; font-family: "Consolas", "Lucida Console", "Droid Sans Mono", "Andale Mono", "Monaco", "Lucida Sans Typewriter"; }
+
+pre { color: #555; line-height: 1.0em; font-family: "Consolas", "Lucida Console", "Droid Sans Mono", "Andale Mono", "Monaco", "Lucida Sans Typewriter"; }
+
+
+a { text-decoration: none; color: #16569A; /* also try #2E85ED, #0033FF, #6C93C6, #1D7BBE, #1D8DD2 */ }
+a:hover, a:hover code { color: #EEEEEE; background-color: #16569A; }
+a:visited, a:visited code { color: #CC3300; }
+a:visited:hover, a:visited:hover code { color: #fff; background-color: #CC3300; }
+
+a.meaningful_link { text-decoration: none; color: #333333; background-color: #EAF9DD; border-bottom: 1px dashed #006400 }
+a.meaningful_link code { text-decoration: none; color: #777; border-bottom: 1px dashed #006400 }
+a.meaningful_link:hover, a.meaningful_link:hover code { background-color: #E0F9C9; }
+a.meaningful_link:visited, a.meaningful_link:visited code { color: #4B0012; }
+a.meaningful_link:visited:hover, a.meaningful_link:visited:hover code{ color: #4B0012; background-color: #ADE78B; }
+
+table[border="1"] { border: 1px solid #ddd; }
+table[border="1"] td, table[border="1"] th { border: 1px solid #ddd; }
+table[cellpadding="3"] td { padding: 0.5em; }
+
+font[size="-1"] { font-size: 0.85em; line-height: 1.5em; }
+font[size="-2"] { font-size: 0.8em; }
+font[size="+2"] { font-size: 1.4em; line-height: 1.3em; padding: 0.4em 0; }
+
+/* Headings */
+h1 { font-size: 1.5em; line-height: 1.286em;}
+
+/* Table colors */
+.TableHeadingColor { background: #ccc; color:#444; } /* Dark mauve */
+.TableSubHeadingColor { background: #ddd; color:#444; } /* Light mauve */
+.TableRowColor { background: #FFFFFF; color:#666; font-size: 0.95em; } /* White */
+.TableRowColor code { color:#000; } /* White */
+
+/* Font used in left-hand frame lists */
+.FrameTitleFont { font-size: 100%; }
+.FrameHeadingFont { font-size: 90%; }
+.FrameItemFont { font-size: 0.9em; line-height: 1.3em;
+}
+/* Java Interfaces */
+.FrameItemFont a i {
+ font-style: normal; color: #666;
+}
+.FrameItemFont a:hover i {
+ font-style: normal; color: #fff; background-color: #666;
+}
+
+/* Navigation bar fonts and colors */
+.NavBarCell1 { background-color:#E0E6DF; } /* Light mauve */
+.NavBarCell1Rev { background-color:#16569A; color:#FFFFFF} /* Dark Blue */
+.NavBarFont1 { }
+.NavBarFont1Rev { color:#FFFFFF; }
+
+.NavBarCell2 { background-color:#FFFFFF; color:#000000}
+.NavBarCell3 { background-color:#FFFFFF; color:#000000}
\ No newline at end of file
| null | train | train | 2016-08-23T19:43:48 | "2016-08-13T17:48:15Z" | bric3 | train |
mockito/mockito/593_597 | mockito/mockito | mockito/mockito/593 | mockito/mockito/597 | [
"keyword_pr_to_issue"
] | e18b07576f8f85c2c5d654a3ccb566adb13c85e7 | 8adcac947b6656431046c88770c4d04f965d8c09 | [
"On it. Thanks!\n"
] | [] | "2016-08-25T03:20:20Z" | [
"docs"
] | Mockito Javadoc has a TODO about hamcrest | ``` java
* TODO rework the documentation, write about hamcrest.
*
*/
@SuppressWarnings("unchecked")
public class Mockito extends ArgumentMatchers {
```
https://github.com/bric3/mockito/blob/18133aa0cb5b51c0472fb8b33ab0a22aa9f0fbf3/src/main/java/org/mockito/Mockito.java#L1207-L1207
Let's remove it or fix it.
| [
"src/main/java/org/mockito/Mockito.java",
"src/main/java/org/mockito/internal/creation/util/SearchingClassLoader.java"
] | [
"src/main/java/org/mockito/Mockito.java"
] | [] | diff --git a/src/main/java/org/mockito/Mockito.java b/src/main/java/org/mockito/Mockito.java
index ffcc5caa12..8ff34cada5 100644
--- a/src/main/java/org/mockito/Mockito.java
+++ b/src/main/java/org/mockito/Mockito.java
@@ -1203,9 +1203,6 @@
* return input1 + input2;
* }})).when(mock).execute(anyString(), anyString());
* </code></pre>
- *
- * TODO rework the documentation, write about hamcrest.
- *
*/
@SuppressWarnings("unchecked")
public class Mockito extends ArgumentMatchers {
@@ -2579,7 +2576,8 @@ public static VerificationMode description(String description) {
}
/**
- * TODO 543 move to MockingDetails
+ * This API will move soon to a different place.
+ * See <a href="https://github.com/mockito/mockito/issues/577">issue 577</a>.
*/
@Deprecated
static MockitoDebugger debug() {
diff --git a/src/main/java/org/mockito/internal/creation/util/SearchingClassLoader.java b/src/main/java/org/mockito/internal/creation/util/SearchingClassLoader.java
deleted file mode 100644
index 645acb4a97..0000000000
--- a/src/main/java/org/mockito/internal/creation/util/SearchingClassLoader.java
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * Copyright (c) 2007 Mockito contributors
- * This program is made available under the terms of the MIT License.
- */
-package org.mockito.internal.creation.util;
-
-import static java.lang.Thread.*;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Inspired on jMock (thanks jMock guys!!!)
- */
-public class SearchingClassLoader extends ClassLoader {
-
- //TODO SF potentially not needed
-
- private final ClassLoader nextToSearch;
-
- public SearchingClassLoader(ClassLoader parent, ClassLoader nextToSearch) {
- super(parent);
- this.nextToSearch = nextToSearch;
- }
-
- public static ClassLoader combineLoadersOf(Class<?>... classes) {
- return combineLoadersOf(classes[0], classes);
- }
-
- private static ClassLoader combineLoadersOf(Class<?> first, Class<?>... others) {
- List<ClassLoader> loaders = new ArrayList<ClassLoader>();
-
- addIfNewElement(loaders, first.getClassLoader());
- for (Class<?> c : others) {
- addIfNewElement(loaders, c.getClassLoader());
- }
-
- // To support Eclipse Plug-in tests.
- // In an Eclipse plug-in, we will not be on the system class loader
- // but in the class loader of the plug-in.
- //
- // Note: I've been unable to reproduce the error in the test suite.
- addIfNewElement(loaders, SearchingClassLoader.class.getClassLoader());
-
- // To support the Maven Surefire plugin.
- // Note: I've been unable to reproduce the error in the test suite.
- addIfNewElement(loaders, currentThread().getContextClassLoader());
-
- //Had to comment that out because it didn't work with in-container Spring tests
- //addIfNewElement(loaders, ClassLoader.getSystemClassLoader());
-
- return combine(loaders);
- }
-
- private static ClassLoader combine(List<ClassLoader> parentLoaders) {
- ClassLoader loader = parentLoaders.get(parentLoaders.size()-1);
-
- for (int i = parentLoaders.size()-2; i >= 0; i--) {
- loader = new SearchingClassLoader(parentLoaders.get(i), loader);
- }
-
- return loader;
- }
-
- private static void addIfNewElement(List<ClassLoader> loaders, ClassLoader c) {
- if (c != null && !loaders.contains(c)) {
- loaders.add(c);
- }
- }
-
- @Override
- protected Class<?> findClass(String name) throws ClassNotFoundException {
- if (nextToSearch != null) {
- return nextToSearch.loadClass(name);
- } else {
- return super.findClass(name); // will throw ClassNotFoundException
- }
- }
-}
\ No newline at end of file
| null | train | train | 2016-08-24T16:48:01 | "2016-08-24T13:31:29Z" | bric3 | train |
mockito/mockito/598_599 | mockito/mockito | mockito/mockito/598 | mockito/mockito/599 | [
"timestamp(timedelta=1302.0, similarity=0.873212348443918)",
"keyword_pr_to_issue"
] | 434579ef4b68311fc58bae28d6dfcae52a26350a | 6da1e65a4ea014b1594efc90ab0841b254efee2a | [] | [
"@szczepiq you could use [`stripIndent`](http://mrhaki.blogspot.com/2010/06/groovy-goodness-strip-leading-spaces.html) for better readability here\n",
"check [out](https://git-scm.com/docs/git-check-mailmap) out git's `.mailmap`, might help in this case\n",
"Thanks for hint and review!!!\n\nI didn't know about this command. I've tried it but it does not give me github user id. However, it does seem interesting and it solves the problem of misspelled names / emails. Wanna help, PR! :)\n",
"I'll give it a shot next time. Thanks for the tip!!!\n\nI'm so used to used to just multi-line string that my brain does not even register that it is hard to read ;)\n"
] | "2016-08-25T16:37:30Z" | [
"continuous integration"
] | Generated release notes contain unsorted and duplicate committers | Generated release notes contain unsorted and duplicate committers
| [
"buildSrc/src/main/groovy/org/mockito/release/notes/vcs/Commit.java",
"buildSrc/src/main/groovy/org/mockito/release/notes/vcs/Contribution.java",
"buildSrc/src/main/groovy/org/mockito/release/notes/vcs/DefaultContributionSet.java",
"buildSrc/src/main/groovy/org/mockito/release/notes/vcs/GitCommit.java",
"buildSrc/src/main/groovy/org/mockito/release/notes/vcs/GitContributionsProvider.java"
] | [
"buildSrc/src/main/groovy/org/mockito/release/notes/vcs/Commit.java",
"buildSrc/src/main/groovy/org/mockito/release/notes/vcs/Contribution.java",
"buildSrc/src/main/groovy/org/mockito/release/notes/vcs/DefaultContributionSet.java",
"buildSrc/src/main/groovy/org/mockito/release/notes/vcs/GitCommit.java",
"buildSrc/src/main/groovy/org/mockito/release/notes/vcs/GitContributionsProvider.java"
] | [
"buildSrc/src/test/groovy/org/mockito/release/notes/vcs/ContributionTest.groovy",
"buildSrc/src/test/groovy/org/mockito/release/notes/vcs/DefaultContributionSetTest.groovy",
"buildSrc/src/test/groovy/org/mockito/release/notes/vcs/GitContributionsProviderTest.groovy"
] | diff --git a/buildSrc/src/main/groovy/org/mockito/release/notes/vcs/Commit.java b/buildSrc/src/main/groovy/org/mockito/release/notes/vcs/Commit.java
index ebe7913890..c6d9218bee 100644
--- a/buildSrc/src/main/groovy/org/mockito/release/notes/vcs/Commit.java
+++ b/buildSrc/src/main/groovy/org/mockito/release/notes/vcs/Commit.java
@@ -7,12 +7,12 @@ public interface Commit {
/**
* Author identifier. For git it would be 'email'
*/
- String getAuthorId();
+ String getAuthorEmail();
/**
* Author display name. For git it would be 'author'
*/
- String getAuthor();
+ String getAuthorName();
/**
* Commit message
diff --git a/buildSrc/src/main/groovy/org/mockito/release/notes/vcs/Contribution.java b/buildSrc/src/main/groovy/org/mockito/release/notes/vcs/Contribution.java
index b26290659b..5f83408445 100644
--- a/buildSrc/src/main/groovy/org/mockito/release/notes/vcs/Contribution.java
+++ b/buildSrc/src/main/groovy/org/mockito/release/notes/vcs/Contribution.java
@@ -7,28 +7,31 @@
class Contribution implements Comparable<Contribution> {
//email identifies the contributor, author alias not necessarily
- final String authorId;
- final String author;
+ final String authorEmail;
+ final String authorName;
final List<Commit> commits = new LinkedList<Commit>();
Contribution(Commit commit) {
- authorId = commit.getAuthorId();
- author = commit.getAuthor();
+ authorEmail = commit.getAuthorEmail();
+ authorName = commit.getAuthorName();
commits.add(commit);
}
Contribution add(Commit commit) {
- assert authorId.equals(commit.getAuthorId());
commits.add(commit);
return this;
}
public String toText() {
- return commits.size() + ": " + author;
+ return commits.size() + ": " + authorName;
}
public int compareTo(Contribution other) {
- return Integer.valueOf(other.getCommits().size()).compareTo(commits.size());
+ int byCommitCount = Integer.valueOf(other.getCommits().size()).compareTo(commits.size());
+ if (byCommitCount != 0) {
+ return byCommitCount;
+ }
+ return this.authorName.toUpperCase().compareTo(other.authorName.toUpperCase());
}
public Collection<Commit> getCommits() {
diff --git a/buildSrc/src/main/groovy/org/mockito/release/notes/vcs/DefaultContributionSet.java b/buildSrc/src/main/groovy/org/mockito/release/notes/vcs/DefaultContributionSet.java
index 65d27c33c0..d0c31fd452 100644
--- a/buildSrc/src/main/groovy/org/mockito/release/notes/vcs/DefaultContributionSet.java
+++ b/buildSrc/src/main/groovy/org/mockito/release/notes/vcs/DefaultContributionSet.java
@@ -5,7 +5,9 @@
import java.util.*;
class DefaultContributionSet implements ContributionSet {
- private final Map<String, Contribution> contributions = new HashMap<String, Contribution>();
+
+ private final List<Contribution> contributions = new LinkedList<Contribution>();
+
private final Collection<Commit> commits = new LinkedList<Commit>();
private final Predicate<Commit> ignoreCommit;
private final Set<String> tickets = new LinkedHashSet<String>();
@@ -20,12 +22,29 @@ void add(Commit commit) {
}
commits.add(commit);
tickets.addAll(commit.getTickets());
- Contribution c = contributions.get(commit.getAuthorId());
- if (c == null) {
- contributions.put(commit.getAuthorId(), new Contribution(commit));
+
+ Contribution existing = findContribution(commit, contributions);
+ if (existing != null) {
+ existing.add(commit);
} else {
- c.add(commit);
+ contributions.add(new Contribution(commit));
+ }
+ }
+
+ private static Contribution findContribution(Commit commit, Iterable<Contribution> contributions) {
+ for (Contribution c : contributions) {
+ //From Git Log we don't know the GitHub user ID, only the email and name.
+ //Sometimes contributors have different email addresses while the same name
+ //This leads to awkward looking release notes, where same author is shown multiple times
+ //We consider the contribution to be the same if any of: email or name is the same
+ //
+ //This approach comes with a caveat. What if the user have same author name, different email and indeed it is a different user?
+ // This scenario is not handled well but it is unlikely and we consider it a trade-off
+ if (c.authorEmail.equals(commit.getAuthorEmail()) || c.authorName.equals(commit.getAuthorName())) {
+ return c;
+ }
}
+ return null;
}
public Collection<Commit> getAllCommits() {
@@ -40,23 +59,11 @@ public String toText() {
StringBuilder sb = new StringBuilder("* Authors: ").append(contributions.size())
.append("\n* Commits: ").append(commits.size());
- for (Map.Entry<String, Contribution> entry : sortByValue(contributions)) {
- Contribution c = entry.getValue();
+ Collections.sort(contributions);
+ for (Contribution c : contributions) {
sb.append("\n * ").append(c.toText());
}
return sb.toString();
}
-
- public static <K, V extends Comparable<V>> List<Map.Entry<K, V>> sortByValue(Map<K, V> map) {
- List<Map.Entry<K, V>> entries = new ArrayList<Map.Entry<K, V>>(map.entrySet());
- Collections.sort(entries, new ByValue<K, V>());
- return entries;
- }
-
- private static class ByValue<K, V extends Comparable<V>> implements Comparator<Map.Entry<K, V>> {
- public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
- return o1.getValue().compareTo(o2.getValue());
- }
- }
}
\ No newline at end of file
diff --git a/buildSrc/src/main/groovy/org/mockito/release/notes/vcs/GitCommit.java b/buildSrc/src/main/groovy/org/mockito/release/notes/vcs/GitCommit.java
index 5c4f4973c2..f1dfc91669 100644
--- a/buildSrc/src/main/groovy/org/mockito/release/notes/vcs/GitCommit.java
+++ b/buildSrc/src/main/groovy/org/mockito/release/notes/vcs/GitCommit.java
@@ -17,11 +17,11 @@ public GitCommit(String email, String author, String message) {
this.tickets = TicketParser.parseTickets(message);
}
- public String getAuthorId() {
+ public String getAuthorEmail() {
return email;
}
- public String getAuthor() {
+ public String getAuthorName() {
return author;
}
diff --git a/buildSrc/src/main/groovy/org/mockito/release/notes/vcs/GitContributionsProvider.java b/buildSrc/src/main/groovy/org/mockito/release/notes/vcs/GitContributionsProvider.java
index 93d5d78901..8e5ba8f050 100644
--- a/buildSrc/src/main/groovy/org/mockito/release/notes/vcs/GitContributionsProvider.java
+++ b/buildSrc/src/main/groovy/org/mockito/release/notes/vcs/GitContributionsProvider.java
@@ -32,6 +32,7 @@ public ContributionSet getContributionsBetween(String fromRev, String toRev) {
String email = entryParts[0].trim();
String author = entryParts[1].trim();
String message = entryParts[2].trim();
+ LOG.info("Loaded commit - email: {}, author: {}, message (trimmed): {}", email, author, message.replaceAll("\n.*", ""));
contributions.add(new GitCommit(email, author, message));
}
}
| diff --git a/buildSrc/src/test/groovy/org/mockito/release/notes/vcs/ContributionTest.groovy b/buildSrc/src/test/groovy/org/mockito/release/notes/vcs/ContributionTest.groovy
index 37d0bd0931..152f1ede5f 100644
--- a/buildSrc/src/test/groovy/org/mockito/release/notes/vcs/ContributionTest.groovy
+++ b/buildSrc/src/test/groovy/org/mockito/release/notes/vcs/ContributionTest.groovy
@@ -8,8 +8,8 @@ class ContributionTest extends Specification {
def c = new Contribution(new GitCommit("a@b", "lad", "m1"))
expect:
- c.author == "lad"
- c.authorId == "a@b"
+ c.authorName == "lad"
+ c.authorEmail == "a@b"
c.toText() == "1: lad"
when: c.add(new GitCommit("a@b", "lad", "m2"))
@@ -32,6 +32,16 @@ class ContributionTest extends Specification {
set as List == [c3, c2, c1]
}
+ def "sorted by commits and uppercase name"() {
+ def d = new Contribution(new GitCommit("d", "d", "")).add(new GitCommit("d", "d", ""))
+ def c = new Contribution(new GitCommit("c", "c", ""))
+ def b = new Contribution(new GitCommit("B", "B", ""))
+ def a = new Contribution(new GitCommit("a", "a", ""))
+
+ expect:
+ new TreeSet([d, c, b, a]) as List == [d, a, b, c]
+ }
+
def "has String representation"() {
def c = new GitCommit("john.doe@gmail.com", "John Doe", "some message")
expect:
diff --git a/buildSrc/src/test/groovy/org/mockito/release/notes/vcs/DefaultContributionSetTest.groovy b/buildSrc/src/test/groovy/org/mockito/release/notes/vcs/DefaultContributionSetTest.groovy
index bac80a590a..26d73c5220 100644
--- a/buildSrc/src/test/groovy/org/mockito/release/notes/vcs/DefaultContributionSetTest.groovy
+++ b/buildSrc/src/test/groovy/org/mockito/release/notes/vcs/DefaultContributionSetTest.groovy
@@ -49,6 +49,35 @@ class DefaultContributionSetTest extends Specification {
then:
c.size() == 1
c[0].message == "good one"
- c[0].author == "A"
+ c[0].authorName == "A"
+ }
+
+ def "contributions by same author with different email"() {
+ contributions.add(new GitCommit("john@x", "john", ""))
+ contributions.add(new GitCommit("john@x", "john", ""))
+ contributions.add(new GitCommit("john@y", "john", "")) //same person, different email
+ contributions.add(new GitCommit("x@y", "x", "")) //different person
+
+ expect:
+ contributions.toText() == """* Authors: 2
+* Commits: 4
+ * 3: john
+ * 1: x"""
+ }
+
+ def "contributions sorted by name if number of commits the same"() {
+ contributions.add(new GitCommit("d@d", "d", ""))
+ contributions.add(new GitCommit("d@d", "d", ""))
+ contributions.add(new GitCommit("c@c", "c", ""))
+ contributions.add(new GitCommit("B@B", "B", ""))
+ contributions.add(new GitCommit("a@a", "a", ""))
+
+ expect:
+ contributions.toText() == """* Authors: 4
+* Commits: 5
+ * 2: d
+ * 1: a
+ * 1: B
+ * 1: c"""
}
}
diff --git a/buildSrc/src/test/groovy/org/mockito/release/notes/vcs/GitContributionsProviderTest.groovy b/buildSrc/src/test/groovy/org/mockito/release/notes/vcs/GitContributionsProviderTest.groovy
index b074506aea..8027e9344b 100644
--- a/buildSrc/src/test/groovy/org/mockito/release/notes/vcs/GitContributionsProviderTest.groovy
+++ b/buildSrc/src/test/groovy/org/mockito/release/notes/vcs/GitContributionsProviderTest.groovy
@@ -30,8 +30,8 @@ john@doe@@info@@John R. Doe@@info@@dummy commit
and:
def commits = c.allCommits as List
- commits[0].author == "Szczepan Faber"
- commits[0].authorId == "szczepiq@gmail.com"
+ commits[0].authorName == "Szczepan Faber"
+ commits[0].authorEmail == "szczepiq@gmail.com"
commits[0].message == "Tidy-up in buildSrc\nnext line"
}
| val | train | 2016-08-25T12:13:33 | "2016-08-25T16:33:03Z" | mockitoguy | train |
mockito/mockito/603_604 | mockito/mockito | mockito/mockito/603 | mockito/mockito/604 | [
"timestamp(timedelta=0.0, similarity=1.0000000000000002)",
"keyword_pr_to_issue"
] | d32a754abd9bb457cd3146d480a42b76e3fcb179 | b669b4fa790171149b8383cc8f9c55cec32de934 | [] | [
"I'd rename this to `Incompatible changes with v1.x`\n",
"Good idea. Thanks!\n"
] | "2016-08-27T14:56:22Z" | [
"continuous integration"
] | Release notes group improvements by labels | For clearer release notes overlook we should group improvements by labels.
This was originally contributed by @szpak, then lost during the early days of continuous integration, now it's back and it will rock!!!
| [
"buildSrc/src/main/groovy/org/mockito/release/gradle/notes/ReleaseNotesExtension.groovy",
"buildSrc/src/main/groovy/org/mockito/release/notes/GitNotesBuilder.java",
"buildSrc/src/main/groovy/org/mockito/release/notes/NotesBuilder.java",
"buildSrc/src/main/groovy/org/mockito/release/notes/improvements/DefaultImprovements.java",
"buildSrc/src/main/groovy/org/mockito/release/notes/improvements/GitHubImprovementsProvider.java",
"buildSrc/src/main/groovy/org/mockito/release/notes/improvements/GitHubTicketFetcher.java",
"buildSrc/src/main/groovy/org/mockito/release/notes/improvements/Improvement.java",
"buildSrc/src/main/groovy/org/mockito/release/notes/improvements/ImprovementsProvider.java",
"gradle/release.gradle"
] | [
"buildSrc/src/main/groovy/org/mockito/release/gradle/notes/ReleaseNotesExtension.groovy",
"buildSrc/src/main/groovy/org/mockito/release/notes/GitNotesBuilder.java",
"buildSrc/src/main/groovy/org/mockito/release/notes/NotesBuilder.java",
"buildSrc/src/main/groovy/org/mockito/release/notes/improvements/DefaultImprovements.java",
"buildSrc/src/main/groovy/org/mockito/release/notes/improvements/GitHubImprovementsProvider.java",
"buildSrc/src/main/groovy/org/mockito/release/notes/improvements/GitHubTicketFetcher.java",
"buildSrc/src/main/groovy/org/mockito/release/notes/improvements/Improvement.java",
"buildSrc/src/main/groovy/org/mockito/release/notes/improvements/ImprovementsProvider.java",
"buildSrc/src/main/groovy/org/mockito/release/util/MultiMap.java",
"gradle/release.gradle"
] | [
"buildSrc/src/test/groovy/org/mockito/release/notes/improvements/DefaultImprovementsTest.groovy",
"buildSrc/src/test/groovy/org/mockito/release/notes/improvements/GitHubTicketFetcherTest.groovy",
"buildSrc/src/test/groovy/org/mockito/release/util/MultiMapTest.groovy"
] | diff --git a/buildSrc/src/main/groovy/org/mockito/release/gradle/notes/ReleaseNotesExtension.groovy b/buildSrc/src/main/groovy/org/mockito/release/gradle/notes/ReleaseNotesExtension.groovy
index 305609be99..05a6c47aaf 100644
--- a/buildSrc/src/main/groovy/org/mockito/release/gradle/notes/ReleaseNotesExtension.groovy
+++ b/buildSrc/src/main/groovy/org/mockito/release/gradle/notes/ReleaseNotesExtension.groovy
@@ -17,6 +17,9 @@ class ReleaseNotesExtension {
private final File workDir;
private final String version;
+ //TODO SF document the behavior
+ Map labels = new LinkedHashMap<String, String>()
+
ReleaseNotesExtension(File workDir, String version) {
this.workDir = workDir
this.version = version
@@ -49,7 +52,7 @@ class ReleaseNotesExtension {
def prev = "v" + getPreviousVersion()
def current = "HEAD"
LOG.lifecycle("Building notes for revisions: {} -> {}", prev, current)
- def newContent = builder.buildNotes(version, prev, current)
+ def newContent = builder.buildNotes(version, prev, current, labels)
newContent
}
diff --git a/buildSrc/src/main/groovy/org/mockito/release/notes/GitNotesBuilder.java b/buildSrc/src/main/groovy/org/mockito/release/notes/GitNotesBuilder.java
index 071e550e35..352c603cab 100644
--- a/buildSrc/src/main/groovy/org/mockito/release/notes/GitNotesBuilder.java
+++ b/buildSrc/src/main/groovy/org/mockito/release/notes/GitNotesBuilder.java
@@ -2,8 +2,8 @@
import org.mockito.release.exec.Exec;
import org.mockito.release.notes.improvements.ImprovementSet;
-import org.mockito.release.notes.improvements.ImprovementsProvider;
import org.mockito.release.notes.improvements.Improvements;
+import org.mockito.release.notes.improvements.ImprovementsProvider;
import org.mockito.release.notes.vcs.ContributionSet;
import org.mockito.release.notes.vcs.ContributionsProvider;
import org.mockito.release.notes.vcs.Vcs;
@@ -12,6 +12,7 @@
import java.io.File;
import java.util.Date;
+import java.util.Map;
class GitNotesBuilder implements NotesBuilder {
@@ -29,14 +30,14 @@ class GitNotesBuilder implements NotesBuilder {
this.authTokenEnvVar = authTokenEnvVar;
}
- public String buildNotes(String version, String fromRevision, String toRevision) {
+ public String buildNotes(String version, String fromRevision, String toRevision, Map<String, String> labels) {
LOG.info("Getting release notes between {} and {}", fromRevision, toRevision);
ContributionsProvider contributionsProvider = Vcs.getGitProvider(Exec.getProcessRunner(workDir));
ContributionSet contributions = contributionsProvider.getContributionsBetween(fromRevision, toRevision);
ImprovementsProvider improvementsProvider = Improvements.getGitHubProvider(authTokenEnvVar);
- ImprovementSet improvements = improvementsProvider.getImprovements(contributions);
+ ImprovementSet improvements = improvementsProvider.getImprovements(contributions, labels);
return new NotesPrinter().printNotes(version, new Date(), contributions, improvements);
}
diff --git a/buildSrc/src/main/groovy/org/mockito/release/notes/NotesBuilder.java b/buildSrc/src/main/groovy/org/mockito/release/notes/NotesBuilder.java
index 7c3cee6c4d..10da616846 100644
--- a/buildSrc/src/main/groovy/org/mockito/release/notes/NotesBuilder.java
+++ b/buildSrc/src/main/groovy/org/mockito/release/notes/NotesBuilder.java
@@ -1,5 +1,7 @@
package org.mockito.release.notes;
+import java.util.Map;
+
/**
* Builds the release notes text
*/
@@ -11,6 +13,8 @@ public interface NotesBuilder {
* @param version the version of the release we're building the notes
* @param fromRevision valid git revision (can be tag name or HEAD)
* @param toRevision valid git revision (can be tag name or HEAD)
+ * @param labels GitHub labels to caption mapping
+ * TODO SF the labels better, currently they are coupled way too much with more generic interfaces, vcs agnostic
*/
- String buildNotes(String version, String fromRevision, String toRevision);
+ String buildNotes(String version, String fromRevision, String toRevision, Map<String, String> labels);
}
\ No newline at end of file
diff --git a/buildSrc/src/main/groovy/org/mockito/release/notes/improvements/DefaultImprovements.java b/buildSrc/src/main/groovy/org/mockito/release/notes/improvements/DefaultImprovements.java
index bf7d55520a..dc605aeb68 100644
--- a/buildSrc/src/main/groovy/org/mockito/release/notes/improvements/DefaultImprovements.java
+++ b/buildSrc/src/main/groovy/org/mockito/release/notes/improvements/DefaultImprovements.java
@@ -1,29 +1,73 @@
package org.mockito.release.notes.improvements;
-import java.util.LinkedList;
-import java.util.List;
+import org.mockito.release.util.MultiMap;
+import java.util.*;
+
+//TODO SF split the formatting from the data structure
class DefaultImprovements implements ImprovementSet {
- private final List<Improvement> improvements = new LinkedList<Improvement>();
+ final List<Improvement> improvements = new LinkedList<Improvement>();
+ private final Map<String, String> labels;
+
+ public DefaultImprovements(Map<String, String> labels) {
+ this.labels = labels;
+ }
public String toText() {
if (improvements.isEmpty()) {
- //TODO SF we should break the build if there are no notable improvements yet the binaries have changed
return "* No notable improvements. See the commits for detailed changes.";
}
StringBuilder sb = new StringBuilder("* Improvements: ").append(improvements.size());
- for (Improvement i : improvements) {
- sb.append("\n * ").append(i.toText());
+ MultiMap<String, Improvement> byLabel = new MultiMap<String, Improvement>();
+ Set<Improvement> remainingImprovements = new LinkedHashSet<Improvement>(improvements);
+
+ //Step 1, find improvements that match input labels
+ //Iterate label first because the input labels determine the order
+ for (String label : labels.keySet()) {
+ for (Improvement i : improvements) {
+ if (i.labels.contains(label) && remainingImprovements.contains(i)) {
+ remainingImprovements.remove(i);
+ byLabel.put(label, i);
+ }
+ }
+ }
+
+ //Step 2, print out the improvements that match input labels
+ for (String label : byLabel.keySet()) {
+ String labelCaption = labels.get(label);
+ Collection<Improvement> labelImprovements = byLabel.get(label);
+ sb.append("\n * ").append(labelCaption).append(": ").append(labelImprovements.size());
+ for (Improvement i : labelImprovements) {
+ sb.append("\n * ").append(i.toText());
+ }
+ }
+
+ //Step 3, print out remaining changes
+ if (!remainingImprovements.isEmpty()) {
+ String indent;
+ //We want clean view depending if there are labelled improvements or not
+ if (byLabel.size() > 0) {
+ indent = " ";
+ sb.append("\n * Remaining changes: ").append(remainingImprovements.size());
+ } else {
+ indent = "";
+ }
+
+ for (Improvement i : remainingImprovements) {
+ sb.append("\n").append(indent).append(" * ").append(i.toText());
+ }
}
return sb.toString();
}
- public void add(Improvement improvement) {
+ public DefaultImprovements add(Improvement improvement) {
improvements.add(improvement);
+ return this;
}
- public void addAll(List<Improvement> improvements) {
+ public DefaultImprovements addAll(List<Improvement> improvements) {
this.improvements.addAll(improvements);
+ return this;
}
}
diff --git a/buildSrc/src/main/groovy/org/mockito/release/notes/improvements/GitHubImprovementsProvider.java b/buildSrc/src/main/groovy/org/mockito/release/notes/improvements/GitHubImprovementsProvider.java
index c81e2c70ff..8258f6964a 100644
--- a/buildSrc/src/main/groovy/org/mockito/release/notes/improvements/GitHubImprovementsProvider.java
+++ b/buildSrc/src/main/groovy/org/mockito/release/notes/improvements/GitHubImprovementsProvider.java
@@ -4,6 +4,8 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import java.util.Map;
+
class GitHubImprovementsProvider implements ImprovementsProvider {
private static final Logger LOGGER = LoggerFactory.getLogger(GitHubImprovementsProvider.class);
@@ -13,9 +15,9 @@ public GitHubImprovementsProvider(String authToken) {
this.authToken = authToken;
}
- public ImprovementSet getImprovements(ContributionSet contributions) {
+ public ImprovementSet getImprovements(ContributionSet contributions, Map<String, String> labels) {
LOGGER.info("Parsing {} commits with {} tickets", contributions.getAllCommits().size(), contributions.getAllTickets().size());
- DefaultImprovements out = new DefaultImprovements();
+ DefaultImprovements out = new DefaultImprovements(labels);
new GitHubTicketFetcher().fetchTickets(authToken, contributions.getAllTickets(), out);
return out;
}
diff --git a/buildSrc/src/main/groovy/org/mockito/release/notes/improvements/GitHubTicketFetcher.java b/buildSrc/src/main/groovy/org/mockito/release/notes/improvements/GitHubTicketFetcher.java
index f3e3396f92..fcce09f99a 100644
--- a/buildSrc/src/main/groovy/org/mockito/release/notes/improvements/GitHubTicketFetcher.java
+++ b/buildSrc/src/main/groovy/org/mockito/release/notes/improvements/GitHubTicketFetcher.java
@@ -1,22 +1,18 @@
package org.mockito.release.notes.improvements;
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.URL;
-import java.net.URLConnection;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.List;
-import java.util.PriorityQueue;
-import java.util.Queue;
+import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.mockito.release.notes.util.IOUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URL;
+import java.net.URLConnection;
+import java.util.*;
+
class GitHubTicketFetcher {
private static final Logger LOG = LoggerFactory.getLogger(GitHubTicketFetcher.class);
@@ -70,6 +66,7 @@ private Queue<Long> queuedTicketNumbers(Collection<String> ticketIds) {
return longs;
}
+ //TODO SF we should be able to unit test the code that parsers JSONObjects
private List<Improvement> wantedImprovements(Collection<Long> tickets, List<JSONObject> issues) {
if(tickets.isEmpty()) {
return Collections.emptyList();
@@ -81,7 +78,8 @@ private List<Improvement> wantedImprovements(Collection<Long> tickets, List<JSON
if (tickets.remove(id)) {
String issueUrl = (String) issue.get("html_url");
String title = (String) issue.get("title");
- pagedImprovements.add(new Improvement(id, title, issueUrl, new HashSet<String>()));
+ Collection<String> labels = extractLabels(issue);
+ pagedImprovements.add(new Improvement(id, title, issueUrl, labels));
if (tickets.isEmpty()) {
return pagedImprovements;
@@ -91,6 +89,15 @@ private List<Improvement> wantedImprovements(Collection<Long> tickets, List<JSON
return pagedImprovements;
}
+ private static Collection<String> extractLabels(JSONObject issue) {
+ Set<String> out = new HashSet<String>();
+ JSONArray labels = (JSONArray) issue.get("labels");
+ for (Object o : labels.toArray()) {
+ JSONObject label = (JSONObject) o;
+ out.add((String) label.get("name"));
+ }
+ return out;
+ }
private static class GitHubIssues {
public static final String RELATIVE_LINK_NOT_FOUND = "none";
diff --git a/buildSrc/src/main/groovy/org/mockito/release/notes/improvements/Improvement.java b/buildSrc/src/main/groovy/org/mockito/release/notes/improvements/Improvement.java
index 4df57c3ad2..b5d7329cb5 100644
--- a/buildSrc/src/main/groovy/org/mockito/release/notes/improvements/Improvement.java
+++ b/buildSrc/src/main/groovy/org/mockito/release/notes/improvements/Improvement.java
@@ -4,10 +4,10 @@
class Improvement {
- private final long id;
+ private final long id; //TODO SF String
private final String title;
private final String url;
- private final Collection<String> labels;
+ final Collection<String> labels;
public Improvement(long id, String title, String url, Collection<String> labels) {
this.id = id;
diff --git a/buildSrc/src/main/groovy/org/mockito/release/notes/improvements/ImprovementsProvider.java b/buildSrc/src/main/groovy/org/mockito/release/notes/improvements/ImprovementsProvider.java
index ca459628a1..f6e0c73529 100644
--- a/buildSrc/src/main/groovy/org/mockito/release/notes/improvements/ImprovementsProvider.java
+++ b/buildSrc/src/main/groovy/org/mockito/release/notes/improvements/ImprovementsProvider.java
@@ -2,7 +2,9 @@
import org.mockito.release.notes.vcs.ContributionSet;
+import java.util.Map;
+
public interface ImprovementsProvider {
- ImprovementSet getImprovements(ContributionSet contributions);
+ ImprovementSet getImprovements(ContributionSet contributions, Map<String, String> labels);
}
diff --git a/buildSrc/src/main/groovy/org/mockito/release/util/MultiMap.java b/buildSrc/src/main/groovy/org/mockito/release/util/MultiMap.java
new file mode 100644
index 0000000000..59b54e3169
--- /dev/null
+++ b/buildSrc/src/main/groovy/org/mockito/release/util/MultiMap.java
@@ -0,0 +1,35 @@
+package org.mockito.release.util;
+
+import java.util.*;
+
+/**
+ * Basic multi-map that contains multiple values per key
+ */
+public class MultiMap<K, V> {
+
+ private final Map<K, Collection<V>> data = new LinkedHashMap<K, Collection<V>>();
+
+ /**
+ * If the key does not exist, null is returned
+ */
+ public Collection<V> get(K key) {
+ return data.get(key);
+ }
+
+ public void put(K key, V value) {
+ Collection<V> elements = get(key);
+ if (elements == null) {
+ elements = new LinkedHashSet<V>();
+ }
+ elements.add(value);
+ data.put(key, elements);
+ }
+
+ public Set<K> keySet() {
+ return data.keySet();
+ }
+
+ public int size() {
+ return data.size();
+ }
+}
diff --git a/gradle/release.gradle b/gradle/release.gradle
index 5b0c5e9701..c2913179f0 100644
--- a/gradle/release.gradle
+++ b/gradle/release.gradle
@@ -25,7 +25,19 @@ apply plugin: 'release-notes'
apply plugin: 'release'
notes {
- notesFile = project.file("doc/release-notes/official.md")
+ notesFile = file("doc/release-notes/official.md")
+ //label captions, in order of importance - this is the order they will appear in the release notes
+ labels = [
+ '1.* incompatible': 'Incompatible changes with previous major version (v1.x)',
+ 'java-9': "Java 9 support",
+ 'java-8': "Java 8 support",
+ 'new feature': "New features",
+ 'BDD': 'Behavior-Driven Development support',
+ 'bug': "Bugfixes",
+ 'enhancement': "Enhancements",
+ 'android': "Android support",
+ 'docs': 'Documentation'
+ ]
}
def dryRun = project.hasProperty('dryRun')
| diff --git a/buildSrc/src/test/groovy/org/mockito/release/notes/improvements/DefaultImprovementsTest.groovy b/buildSrc/src/test/groovy/org/mockito/release/notes/improvements/DefaultImprovementsTest.groovy
index 5557bb3610..410a96cfe0 100644
--- a/buildSrc/src/test/groovy/org/mockito/release/notes/improvements/DefaultImprovementsTest.groovy
+++ b/buildSrc/src/test/groovy/org/mockito/release/notes/improvements/DefaultImprovementsTest.groovy
@@ -1,28 +1,69 @@
package org.mockito.release.notes.improvements
import spock.lang.Specification
-import spock.lang.Subject
class DefaultImprovementsTest extends Specification {
- @Subject improvements = new DefaultImprovements()
-
def "empty improvements"() {
expect:
- improvements.toText() == "* No notable improvements. See the commits for detailed changes."
+ new DefaultImprovements([:]).toText() == "* No notable improvements. See the commits for detailed changes."
}
- def "with improvements"() {
- improvements.add(new Improvement(100, "Fix bug x", "http://issues/100", ["bug"]))
- improvements.add(new Improvement(122, "Javadoc update", "http://url/122", []))
- improvements.add(new Improvement(125, "Some enh", "http://issues/125", ["enhancement", "custom"]))
- improvements.add(new Improvement(126, "Some other enh", "http://issues/126", ["enhancement"]))
+ def "set of improvements in order"() {
+ def is = new DefaultImprovements([bug: "Bugfixes", enhancement: "Enhancements"])
+ .add(new Improvement(100, "Fix bug x", "http://issues/100", ["bug"]))
+ .add(new Improvement(122, "Javadoc update", "http://url/122", []))
+ .add(new Improvement(125, "Some enh", "http://issues/125", ["java-8", "enhancement", "bug"]))
+ .add(new Improvement(126, "Some other enh", "http://issues/126", ["enhancement"]))
+ .add(new Improvement(130, "Refactoring", "http://issues/130", ["java-8", "refactoring"]))
expect:
- improvements.toText() == """* Improvements: 4
- * Fix bug x [(#100)](http://issues/100)
- * Javadoc update [(#122)](http://url/122)
- * Some enh [(#125)](http://issues/125)
- * Some other enh [(#126)](http://issues/126)"""
+ is.toText() == """* Improvements: 5
+ * Bugfixes: 2
+ * Fix bug x [(#100)](http://issues/100)
+ * Some enh [(#125)](http://issues/125)
+ * Enhancements: 1
+ * Some other enh [(#126)](http://issues/126)
+ * Remaining changes: 2
+ * Javadoc update [(#122)](http://url/122)
+ * Refactoring [(#130)](http://issues/130)"""
+ }
+
+ def "no matching labels"() {
+ given:
+ def is = new DefaultImprovements([bug: "Bugfixes"])
+ .add(new Improvement(10, "Issue 10", "10", []))
+
+ expect: "the formatting is simplified"
+ is.toText() == """* Improvements: 1
+ * Issue 10 [(#10)](10)"""
+ }
+
+ def "no duplicated improvements"() {
+ given:
+ def is = new DefaultImprovements([bug: "Bugfixes", refactoring: "Refactorings"])
+ .add(new Improvement(10, "Issue 10", "10", ["bug", "refactoring"]))
+ .add(new Improvement(11, "Issue 11", "11", ["refactoring", "bug"]))
+
+ expect: "no duplication even though labels are overused"
+ is.toText() == """* Improvements: 2
+ * Bugfixes: 2
+ * Issue 10 [(#10)](10)
+ * Issue 11 [(#11)](11)"""
+ }
+
+ def "the order of labels is determined"() {
+ given:
+ //input label captions determine the order of labels:
+ def labels = [p0: "Priority 0", p1: "Priority 1"]
+ def imp1 = new Improvement(10, "Issue 10", "10", ["p0"])
+ def imp2 = new Improvement(11, "Issue 11", "11", ["p1"])
+
+ when:
+ def improvements = new DefaultImprovements(labels).addAll([imp1, imp2]).toText()
+ def reordered = new DefaultImprovements(labels).addAll([imp2, imp1]).toText()
+
+ then: "The order of labels is determined"
+ improvements == reordered
}
}
diff --git a/buildSrc/src/test/groovy/org/mockito/release/notes/improvements/GitHubTicketFetcherTest.groovy b/buildSrc/src/test/groovy/org/mockito/release/notes/improvements/GitHubTicketFetcherTest.groovy
index 9021379993..3a41b136bb 100644
--- a/buildSrc/src/test/groovy/org/mockito/release/notes/improvements/GitHubTicketFetcherTest.groovy
+++ b/buildSrc/src/test/groovy/org/mockito/release/notes/improvements/GitHubTicketFetcherTest.groovy
@@ -10,12 +10,15 @@ class GitHubTicketFetcherTest extends Specification {
@Subject fetcher = new GitHubTicketFetcher()
- //TODO SF tidy up this and the test subject
+ //This is an integration test
+ //It's not ideal but it gives us a good smoke test
+ //So far it is not problematic to maintain :)
def "fetches improvements from GitHub"() {
- def impr = new DefaultImprovements()
+ def impr = new DefaultImprovements([:])
def readOnlyToken = "a0a4c0f41c200f7c653323014d6a72a127764e17"
when: fetcher.fetchTickets(readOnlyToken, ['109', '108', '99999', '112'], impr)
then:
+ impr.improvements.get(0).labels == ["enhancement"] as Set
impr.toText() == """* Improvements: 2
* Allow instances of other classes in AdditionalAnswers.delegatesTo [(#112)](https://github.com/mockito/mockito/issues/112)
* Clarify Spy vs Mock CALLS_REAL_METHODS [(#108)](https://github.com/mockito/mockito/issues/108)"""
diff --git a/buildSrc/src/test/groovy/org/mockito/release/util/MultiMapTest.groovy b/buildSrc/src/test/groovy/org/mockito/release/util/MultiMapTest.groovy
new file mode 100644
index 0000000000..5a7b03fe48
--- /dev/null
+++ b/buildSrc/src/test/groovy/org/mockito/release/util/MultiMapTest.groovy
@@ -0,0 +1,30 @@
+package org.mockito.release.util
+
+import spock.lang.Specification
+
+class MultiMapTest extends Specification {
+
+ def "empty multi map"() {
+ def map = new MultiMap<String, String>()
+
+ expect:
+ map.size() == 0
+ map.keySet().empty
+ }
+
+ def "contains multiple values per key"() {
+ def map = new MultiMap<String, String>();
+ map.put("1", "x")
+ map.put("1", "y")
+ map.put("2", "z")
+
+ expect:
+ map.get("1") == ["x", "y"] as Set
+ map.get("2") == ["z"] as Set
+ map.size() == 2
+ map.keySet() == ["1", "2"] as Set
+
+ //questionable but I decided to keep the impl simple:
+ map.get("3") == null
+ }
+}
| val | train | 2016-08-27T14:01:15 | "2016-08-27T14:17:05Z" | mockitoguy | train |
mockito/mockito/497_615 | mockito/mockito | mockito/mockito/497 | mockito/mockito/615 | [
"keyword_pr_to_issue"
] | b669b4fa790171149b8383cc8f9c55cec32de934 | aef4dad12079a919d3813a5c690c7608032d5740 | [
"I have a hacky workaround using Guava's `TypeToken`:\n\n```\n private static final MockUtil mockUtil = new MockUtil();\n\n @SuppressWarnings(\"unchecked\")\n private static <T> T createSmartDeepMock(TypeToken<T> mockType) {\n return (T) mock(mockType.getRawType(), createSmartDeepMockAnswer(mockType));\n }\n\n private static Answer<?> createSmartDeepMockAnswer(TypeToken<?> mockType) {\n Map<Method, Object> mocks = new LinkedHashMap<>();\n\n return invocation -> {\n Method method = invocation.getMethod();\n if (mocks.containsKey(method)) {\n return mocks.get(method);\n }\n\n Type returnType = method.getGenericReturnType();\n TypeToken<?> resolvedReturnType = mockType.resolveType(returnType);\n Class<?> returnClass = resolvedReturnType.getRawType();\n\n if (!mockUtil.isTypeMockable(returnClass)) {\n return Mockito.RETURNS_DEFAULTS.answer(invocation);\n } else {\n Object mock = createSmartDeepMock(resolvedReturnType);\n mocks.put(method, mock);\n return mock;\n }\n };\n }\n```\n"
] | [] | "2016-08-30T21:10:08Z" | [] | DEEP_STUBS tries to mock final class | ```
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>1.10.19</version>
<scope>test</scope>
</dependency>
```
```
$ java -version
java version "1.8.0_91"
Java(TM) SE Runtime Environment (build 1.8.0_91-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.91-b14, mixed mode)
```
```
import static org.junit.Assert.assertNull;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import org.junit.Test;
public class MockitoBug {
public interface Supplier<T> {
public T get();
}
public interface StringSupplier extends Supplier<String> {}
public interface InheritedSupplier extends StringSupplier {}
@Test
public void deepStubs() {
StringSupplier mock = mock(StringSupplier.class, RETURNS_DEEP_STUBS);
String s = mock.get();
assertNull(s);
}
@Test
public void inheritedDeepStubs() {
InheritedSupplier mock = mock(InheritedSupplier.class, RETURNS_DEEP_STUBS);
String s = mock.get(); // ClassCastException
assertNull(s);
}
}
```
```
java.lang.ClassCastException: org.mockito.internal.creation.cglib.ClassImposterizer$ClassWithSuperclassToWorkAroundCglibBug$$EnhancerByMockitoWithCGLIB$$322ebf6e cannot be cast to java.lang.String
at MockitoBug.inheritedDeepStubs(MockitoBug.java:26)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
```
I expect the behavior for `StringSupplier` and `InheritedSupplier` to be the same: return `null` for `get`. However, `InheritedSupplier` tries to return a mock `Object` for `get`.
| [
"src/main/java/org/mockito/internal/util/reflection/GenericMetadataSupport.java"
] | [
"src/main/java/org/mockito/internal/util/reflection/GenericMetadataSupport.java"
] | [
"src/test/java/org/mockitousage/stubbing/DeepStubbingTest.java"
] | diff --git a/src/main/java/org/mockito/internal/util/reflection/GenericMetadataSupport.java b/src/main/java/org/mockito/internal/util/reflection/GenericMetadataSupport.java
index eedfebd76b..8efd384992 100644
--- a/src/main/java/org/mockito/internal/util/reflection/GenericMetadataSupport.java
+++ b/src/main/java/org/mockito/internal/util/reflection/GenericMetadataSupport.java
@@ -251,7 +251,7 @@ public GenericMetadataSupport resolveGenericReturnType(Method method) {
private GenericMetadataSupport resolveGenericType(Type type, Method method) {
if (type instanceof Class) {
- return new NotGenericReturnTypeSupport(type);
+ return new NotGenericReturnTypeSupport(this, type);
}
if (type instanceof ParameterizedType) {
return new ParameterizedReturnType(this, method.getTypeParameters(), (ParameterizedType) type);
@@ -494,8 +494,11 @@ public Class<?> rawType() {
private static class NotGenericReturnTypeSupport extends GenericMetadataSupport {
private final Class<?> returnType;
- public NotGenericReturnTypeSupport(Type genericReturnType) {
+ public NotGenericReturnTypeSupport(GenericMetadataSupport source, Type genericReturnType) {
returnType = (Class<?>) genericReturnType;
+ this.contextualActualTypeParameters = source.contextualActualTypeParameters;
+
+ registerAllTypeVariables(returnType);
}
@Override
| diff --git a/src/test/java/org/mockitousage/stubbing/DeepStubbingTest.java b/src/test/java/org/mockitousage/stubbing/DeepStubbingTest.java
index fba55af035..e20f36c29d 100644
--- a/src/test/java/org/mockitousage/stubbing/DeepStubbingTest.java
+++ b/src/test/java/org/mockitousage/stubbing/DeepStubbingTest.java
@@ -14,6 +14,7 @@
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.net.Socket;
+import java.util.List;
import java.util.Locale;
import static junit.framework.TestCase.*;
@@ -64,7 +65,15 @@ public String getLongName() {
}
static final class FinalClass {}
-
+
+ interface First {
+ Second getSecond();
+
+ String getString();
+ }
+
+ interface Second extends List<String> {}
+
@Test
public void myTest() throws Exception {
SocketFactory sf = mock(SocketFactory.class, RETURNS_DEEP_STUBS);
@@ -310,4 +319,11 @@ public void shouldFailGracefullyWhenClassIsFinal() throws Exception {
//then
assertEquals(value, person.getFinalClass());
}
+
+ @Test
+ public void deep_stub_does_not_try_to_mock_generic_final_classes() {
+ First first = mock(First.class, RETURNS_DEEP_STUBS);
+ assertNull(first.getString());
+ assertNull(first.getSecond().get(0));
+ }
}
| val | train | 2016-08-28T16:04:39 | "2016-07-16T17:59:01Z" | JeffFaer | train |
mockito/mockito/625_626 | mockito/mockito | mockito/mockito/625 | mockito/mockito/626 | [
"timestamp(timedelta=1.0, similarity=0.887892184341997)"
] | 310a0f3d7c004523a62c85f65cf9047acd855a8b | 732a3208cc853b6c1ccd96a2a309903c85bd2059 | [] | [] | "2016-09-06T14:01:34Z" | [] | Tweak javadoc | - some feature indicates 2.1.0 in javadoc but it should 3.0.0
| [
"src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsMoreEmptyValues.java"
] | [
"src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsMoreEmptyValues.java"
] | [] | diff --git a/src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsMoreEmptyValues.java b/src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsMoreEmptyValues.java
index 5d37aacbfa..2c20525057 100644
--- a/src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsMoreEmptyValues.java
+++ b/src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsMoreEmptyValues.java
@@ -13,7 +13,7 @@
import java.lang.reflect.Array;
/**
- * It's likely this implementation will be used by default by every Mockito 2.1.0 mock.
+ * It's likely this implementation will be used by default by every Mockito 3.0.0 mock.
* <p>
* Currently <b>used only</b> by {@link Mockito#RETURNS_SMART_NULLS}
* <p>
| null | train | train | 2016-09-06T08:13:21 | "2016-09-06T13:58:20Z" | mockitoguy | train |
mockito/mockito/594_627 | mockito/mockito | mockito/mockito/594 | mockito/mockito/627 | [
"keyword_pr_to_issue"
] | 9b08c0834fe5cfcab1f188c3a5511e08c0268904 | 15cf2312df360f11282f3dec7915d4648e4ffb21 | [
"@bric3, this is great. Thank you for finally describing the workflow!!!\n",
"~~I'll try to work on this this week. Yet this ticket is not mandatory for releasing (hence no milestone assignment).~~\n\nEDIT in the end I couldn't find time this week fo this\n",
"The plan makes perfect sense. Let's zoom into implementation details. For example:\n1. Create 2 active branches: \"master\" and \"release\"\n2. Set version.properties in \"master\" to 3.0.0-beta.1, automatically publish per push\n3. Set version.properties in \"release\" to 2.1.0-rc.1, automatically publish per push (?)\n a. At some point change version.properties in \"release\" to \"2.1.0\", automatically publish per push\n\nI know that travis can now get version from commit message. How would this work for keeping 2 active branches / publishing RCs?\n",
"If you want to publish a RC for the v2 branch, you checkout that branch, then commit with `Prepare release candidate [ci-release v2.1.0-RC.1]` on that branch and it should be good to go.\n",
"I'd rather go for a branch out model like described in https://github.com/mockito/mockito/issues/594#issue-172969427, so we (and interested parties) can still release a important patch for an old mockito version.\n",
"@szczepiq I'm waiting on the release note of #582 to branch out to `release/2.x`\n",
"That should be working fine right? With the versionproperties separate in each branch (and the manual releases).\n",
"Yes, but not with a single `release` branch.\n\n> 1. Create 2 active branches: \"master\" and \"release\"\n",
"Oh sorry, I misread that. Yes we must have a release branch for every major semver version. Reading is hard sometimes :stuck_out_tongue_winking_eye: So +1 for me for @bric3 model, which I also was trying to describe.\n",
"When do we use magic incantation in the commit message and when not?\n\nThere is an approach with fully automated releases:\n1. Create \"v2\" branch (or something like that), that still publishes Beta.\n2. Test it out, so that Beta is neatly released from \"v2\".\n3. Change version in \"v2\" into RC, remove top of the release notes, push.\n4. Iterate on the fixes, every push creates new RC.\n5. At some point, change version to \"2.1.0\", push.\n6. Any push to \"v2\" publishes new 2.1.*\n\nFor 2 active dev branches (e.g. mockito3 beta in master and v2) we need to split release notes (e.g. notes/v2.md and notes/v3.md). It's not blocking v2 release, we can do it later.\n\nAwesome, I'm getting excited, we'll have RC before JavaOne! :)\n",
"> Any push to \"v2\" publishes new 2.1.*\n\nI would instead have the drone only push betas. E.g. 2.1.1-beta.*.\n\nOn Thu, 1 Sep 2016, 07:18 Szczepan Faber, notifications@github.com wrote:\n\n> When do we use magic incantation in the commit message and when not?\n> \n> There is an approach with fully automated releases:\n> 1. Create \"v2\" branch (or something like that), that still publishes\n> Beta.\n> 2. Test it out, so that Beta is neatly released from \"v2\".\n> 3. Change version in \"v2\" into RC, remove top of the release notes,\n> push.\n> 4. Iterate on the fixes, every push creates new RC.\n> 5. At some point, change version to \"2.1.0\", push.\n> 6. Any push to \"v2\" publishes new 2.1.*\n> \n> For 2 active dev branches (e.g. mockito3 beta in master and v2) we need to\n> split release notes (e.g. notes/v2.md and notes/v3.md). It's not blocking\n> v2 release, we can do it later.\n> \n> Awesome, I'm getting excited, we'll have RC before JavaOne! :)\n> \n> —\n> You are receiving this because you commented.\n> \n> Reply to this email directly, view it on GitHub\n> https://github.com/mockito/mockito/issues/594#issuecomment-243978550,\n> or mute the thread\n> https://github.com/notifications/unsubscribe-auth/AFrDbxJRdQ7Q3PHv8p0kxCZveqCVpp9Fks5qlmA6gaJpZM4JsE40\n> .\n",
"No more betas please :) Continuous delivery is signature feature of Mockito project.\n",
"While that is true, for every pull request we would release a new patch version. I am not a fan of that. Preferably update less, but more meaningful for the end-user. If you are continuously producing new non-beta artifacts, I think end-users tend to wait with upgrading instead. It's sad that gradle/maven can't import from master instead, but I think we should try to keep our semver versions clean.\n",
"This is an old debate, that we had on the mailing list a couple of years ago.\n\n@szczepiq I know you are an advocate of each commit can be a release, I heard about your talk. This is really nice pushing forward for continuous delivery however I don't agree that every single commit should be released especially on libraries. For some projects it maybe ok, but for some I'd be more conservative.\n\nFor example 1.10.x series was nice but felt less stable to many users. Some merged PR introduced the Mockito rule and the API had to be changed. Some incorrect behavior had to be fixed, some were fixed later in the beta. I'm not sure this builds trust in the library.\n\nAlso with this big changes cannot fit in your model : should we have released in between PR of the JUnit feature, after all there was enough interesting and working features already. \nFor mockito 3 we will target java 8, there's a lot of clean up, maybe some rewriting, doing so we may break things, that happens even with tests, this phase should not be seen as something else than a beta.\n",
"> For 2 active dev branches (e.g. mockito3 beta in master and v2) we need to split release notes (e.g. notes/v2.md and notes/v3.md). It's not blocking v2 release, we can do it later. \n\nExactly. Note that 2.x branch should see most activities, but the scope is limited. And after 2.1 we could declare 2.x in_maintainance_ mode.\n",
"I'm happy to rekindle the discussion. If you convince me, I win win because I learn more :)\n\n> Also with this big changes cannot fit in your model\n\nWhy cannot the big feature be developed in a branch?\n\n> For example 1.10.x series was nice but felt less stable to many users.\n\n\"felt less stable\" - do you have concrete data?\n\nSome thoughts:\n- users don't have to upgrade to every version\n- we could do minor version bump every month or so, combine the release notes and do bigger announcement\n\n> Some merged PR introduced the Mockito rule and the API had to be changed\n> Some incorrect behavior had to be fixed, some were fixed later in the beta.\n\nI'm not convinced that this is a problem of CD. This could happen in the traditional release model, too.\n\nI'm a fan of CD because:\n- it forces to care about quality, documentation, compatibility of every PR\n- it gives features to users faster\n- it provides features incrementally, the smaller the change, the lower chance of regression\n- it helps with project maintenance - users test and pick up new versions faster\n\nLet's say that we don't do CD. How would the release look like? You would release once in a while using magic String in commit message?\n",
"@szczepiq I don't say abandon CD, I like the CD, for the reason you mentioned. But let's not make a release per se, like today maybe label them as `beta` or `build` this builds shows progress and still allows interested users to try mockito current work.\n\n> > Also with this big changes cannot fit in your model\n> \n> Why cannot the big feature be developed in a branch?\n\nYes they can, but sometime those are incomplete or buggy. Like having thread safety, or whatever else. \nAnd even so when these features land it is just possible to go back on some features, APIs, behaviour that was developed in a previous release.\n",
"> > For example 1.10.x series was nice but felt less stable to many users.\n> \n> \"felt less stable\" - do you have concrete data?\n\nActually this _data_ comes the issue and PR we had at that time, questions asked on SO and from my own colleagues experience. However I don't have those question/gh issues in mind as it's been a long time ago.\n",
"> - users don't have to upgrade to every version\n\nIndeed.\n\n> - we could do minor version bump every month or so, combine the release notes and do bigger announcement\n\nYeah that works, but with previous point I think this could just be intermediary _preview_ / _milestone_ releases along with other regular beta builds.\n",
"> Yes they can, but sometime those are incomplete or buggy. Like having thread safety, or whatever else.\n> And even so when these features land it is just possible to go back on some features, APIs, behaviour that was developed in a previous release.\n\nLet's not push buggy or incomplete features :) The stability problem should be solved by high quality PRs, well designed, documented, and tested.\n\nWe can push \"build\" versions, etc. from branch if we see that it's a good idea.\n\n> Actually this data comes the issue and PR we had at that time, questions asked on SO and from my own colleagues experience. However I don't have those question/gh issues in mind as it's been a long time ago.\n\nIt seems there aren't concrete datapoints at this time. I'd rather not change the CD strategy, wait for concrete data, re-evaluate as needed.\n",
"In the end I couldn't work on it this week, I'll try next week.\n"
] | [] | "2016-09-08T03:37:19Z" | [
"continuous integration"
] | Make the build script aware of the release branch | Releasing from the `master` branch has advantages developer wise, however when users that are hit by a bug and that `master` has significantly changed we cannot propose a stable enough release (example 2.0 betas releases, even the 1.10.x series had some instabilities API wise).
In order to enable the team and contributors in general to fix issues while still allowing bigger work on the next version I propose the following change in branch and release _process_.
1. Branch out to `release/2.x`
1. Release `2.0.0`
2. Patch issue
3. Release `2.0.1`
4. Additional work on 2.1
5. Release `2.1.0`
6. ...
7. Forget about `2.1.x`
8. Critical fixes only get released
2. Upgrade `master` to `3.0.0-beta-<build number>`
1. Start mockito `3.0.0` progress there (like java 8 only, drop APIs)
Also with recent change in the build script we could now release and check the release version with the branch.
See
- https://github.com/mockito/mockito/commit/b6a402f16e9222605638efe9b57eccc80a197f9e#diff-33cf41d9669aaef72ca19c641dc57d47R68
- https://github.com/mockito/mockito/issues/586#issuecomment-242076979
- https://github.com/mockito/mockito/pull/483#issuecomment-231323266
| [
"doc/release-notes/official.md",
"gradle/release.gradle",
"src/main/java/org/mockito/Mockito.java",
"version.properties"
] | [
"doc/release-notes/official.md",
"gradle/release.gradle",
"src/main/java/org/mockito/Mockito.java",
"version.properties"
] | [] | diff --git a/doc/release-notes/official.md b/doc/release-notes/official.md
index ce90a6ede3..5058739575 100644
--- a/doc/release-notes/official.md
+++ b/doc/release-notes/official.md
@@ -1,3 +1,26 @@
+### 2.1.0-beta.125 (2016-09-08 03:42 UTC)
+
+* Authors: 4
+* Commits: 24
+ * 15: Szczepan Faber
+ * 5: Continuous Delivery Drone
+ * 3: Brice Dutheil
+ * 1: Divyansh Gupta
+* Improvements: 3
+ * Documentation: 1
+ * Update documentation links in travis config comments [(#558)](https://github.com/mockito/mockito/pull/558)
+ * Remaining changes: 2
+ * Ensured javadocs are correct [(#626)](https://github.com/mockito/mockito/pull/626)
+ * Tweak javadoc [(#625)](https://github.com/mockito/mockito/issues/625)
+
+### 2.1.0-beta.124 (2016-09-07 04:36 UTC)
+
+* Authors: 2
+* Commits: 12
+ * 11: Szczepan Faber
+ * 1: Continuous Delivery Drone
+* No notable improvements. See the commits for detailed changes.
+
### 2.1.0-beta.123 (2016-09-06 15:01 UTC)
* Authors: 4
diff --git a/gradle/release.gradle b/gradle/release.gradle
index 78ed82995b..d8005a59a8 100644
--- a/gradle/release.gradle
+++ b/gradle/release.gradle
@@ -83,8 +83,8 @@ task("releaseNeeded") {
def skippedByCommitMessage = commitMessage?.contains(skipReleaseCommitMessage)
def customVersion = (commitMessage =~ customReleaseVersionPattern)
ext.needed = dryRun || customVersion.matches() || (pr == 'false' && isReleasableBranch(branch) && !comparePublications.publicationsEqual && skipEnvVariable != 'true' && !skippedByCommitMessage)
- logger.lifecycle("Release needed: {}, branch: {}, pull request: {}, dry run: {}, publications equal: {}, skip env variable: {}, skipped by message: {}, customVersion: {}.",
- needed, branch, pr, dryRun, comparePublications.publicationsEqual, skipEnvVariable, skippedByCommitMessage, customVersion.matches())
+ logger.lifecycle("Release needed: {}, releasable branch: {}, pull request: {}, dry run: {}, publications equal: {}, skip env variable: {}, skipped by message: {}, customVersion: {}.",
+ needed, isReleasableBranch(branch), pr, dryRun, comparePublications.publicationsEqual, skipEnvVariable, skippedByCommitMessage, customVersion.matches())
}
}
@@ -94,7 +94,7 @@ bintrayUpload {
doFirst {
logger.lifecycle troubleshootingInfo
if (dryRun) {
- logger.lifecycle "Dry-running the release"
+ logger.lifecycle "Dry-running the release! Although 'bintrayUpload' is executed, it won't upload any binaries ('bintrayUpload.dryRun' property is set)."
}
}
}
@@ -118,7 +118,8 @@ releaseSteps {
step("ensure good chunk of recent commits is pulled for release notes automation") {
//Travis default clone is pretty shallow
- run "git", "pull", "--depth", "500"
+ //Loading extra 1K commits (1.x -> 2.x had ~700 commits)
+ run "git", "pull", "--depth", "1000"
}
def gitAuthor
@@ -128,7 +129,8 @@ releaseSteps {
step("commit updated javadoc into gh-pages branch") { commitUpdatedJavadoc(buildInfo) }
/*
- Now we'll start operating on master. This introduces a problem - someone might have pushed changes *after* release process has started
+ Now we'll start operating on branch that we want to release.
+ This introduces a problem - someone might have pushed changes *after* release process has started
What can happen:
- bintrayUpload will fail saying that the version is already released
- git push fails saying that the pull is needed
@@ -136,7 +138,7 @@ releaseSteps {
- see 'TROUBLESHOOTING' section at the top of this file
*/
- step("start operating on master") { run "git", "checkout", "master" }
+ step("start operating on $System.env.TRAVIS_BRANCH") { run "git", "checkout", System.env.TRAVIS_BRANCH }
step("update release notes") { project.notes.updateReleaseNotes() }
@@ -146,11 +148,11 @@ releaseSteps {
step("create new version tag") { createTag(buildInfo, "v${currentVersion}".toString()) }
.rollback { run "git", "tag", "-d", "v${currentVersion}".toString()}
- step("commit incremented version on master") { commitIncrementedVersion(currentVersion, buildInfo, project.versionFile) }
+ step("commit incremented version on $System.env.TRAVIS_BRANCH") { commitIncrementedVersion(currentVersion, buildInfo, project.versionFile) }
.rollback { run "git", "reset", "--hard", "HEAD^" }
step("push changes to all involved branches") {
- def pushCommandLine = ["git", "push", pushTarget, "master", "gh-pages", "v$currentVersion", "-q"]
+ def pushCommandLine = ["git", "push", pushTarget, System.env.TRAVIS_BRANCH, "gh-pages", "v$currentVersion", "-q"]
if (dryRun) {
pushCommandLine << '--dry-run'
}
diff --git a/src/main/java/org/mockito/Mockito.java b/src/main/java/org/mockito/Mockito.java
index 35c06f5496..7baeea8cbe 100644
--- a/src/main/java/org/mockito/Mockito.java
+++ b/src/main/java/org/mockito/Mockito.java
@@ -73,14 +73,14 @@
*
* <h3 id="0">0. <a class="meaningful_link" href="#verification">Migrating to 2.1.0</a></h3>
*
- * In order to continue improving Mockito and further improve the unit testing experience, we want you to upgrade to 2.0.
+ * In order to continue improving Mockito and further improve the unit testing experience, we want you to upgrade to 2.1.0!
* Mockito follows <a href="http://semver.org/">semantic versioning</a>
* and contains breaking changes only on major version upgrades.
* In the lifecycle of a library, breaking changes are necessary
* to roll out a set of brand new features that alter the existing behavior or even change the API.
* We hope that you enjoy Mockito 2.1.0!
* <p>
- * List of breaking changes:
+ * List of breaking changes: TODO 596
* <ul>
* <li>Mockito is decoupled from Hamcrest and custom matchers API has changed, see {@link ArgumentMatcher}
* for rationale and migration guide.</li>
@@ -1233,7 +1233,7 @@ public class Mockito extends ArgumentMatchers {
* <code>ReturnsSmartNulls</code> first tries to return ordinary return values (see {@link ReturnsMoreEmptyValues})
* then it tries to return SmartNull. If the return type is final then plain null is returned.
* <p>
- * <code>ReturnsSmartNulls</code> will be probably the default return values strategy in Mockito 2.0.
+ * <code>ReturnsSmartNulls</code> will be probably the default return values strategy in Mockito 3.0.0
* <p>
* Example:
* <pre class="code"><code class="java">
diff --git a/version.properties b/version.properties
index b0469d5032..0035f85bad 100644
--- a/version.properties
+++ b/version.properties
@@ -1,2 +1,2 @@
-version=2.1.0-beta.124
+version=2.1.0-beta.126
mockito.testng.version=1.0
| null | test | train | 2016-09-06T17:01:55 | "2016-08-24T14:37:43Z" | bric3 | train |
mockito/mockito/596_628 | mockito/mockito | mockito/mockito/596 | mockito/mockito/628 | [
"keyword_issue_to_pr"
] | 15cf2312df360f11282f3dec7915d4648e4ffb21 | bffa8f2c1dd9e9399e5268f8b7b4604e163c6e6f | [
"There were separate issues for these points. For example the last point was already fixed by @brice3 in a recent PR\n",
"This list nicely summarizes the incompatible changes: https://github.com/mockito/mockito/issues?utf8=✓&q=label%3A%221.*%20incompatible%22%20\n",
"@bric3 has started the migration guide: https://github.com/mockito/mockito/wiki/What's-new-in-mockito-2\n",
"Migration guide has been updated and I did a small spell check. That LGTM.\n",
"Thanks @TimvdLippe\n@raphw @szpak @marcingrzejszczak @szczepiq if you want to add other stuff to this migration guide ?\n",
"Sorry, I won't find time for anything before JavaZone next week is over. Afterwards, I will have a look!\n",
"Given long weekend coming, I can commit to finalize my review / amendments by the end of Wed next week (9/7). Apologies it is not as fast as the crew would like!\n\nKeep in mind that you don't need me to pull the trigger!!!\n\nGuys, we're so close now! It's exciting :)))))\n",
"@raphw No problem. Enjoy JavaZone. Also do some advertisement for mockito 2 ;)\n",
"I've checked out the migration guide and I found it really good. I was missing an example of a default method but I think @TimvdLippe added that.\n\nI haven't done much (to say the least) with regards to this release so I don't have much to write from myself. Like I told @szczepiq and @bric3 I'm overwhelmed with other projects but I'll try to be more active in the upcoming months (don't promise anything though :/ ).\n\nDefinitely I can take over testing questions and support if there are some! :)\n",
"I just remembered this, have to add tomorrow: lazy verification.\n",
"Lazy verification mention added: https://github.com/mockito/mockito/wiki/What's-new-in-Mockito-2/_compare/e0b49e128f97d703e616c01f0a4893da5295098e...10ba7530dff7a72ef869a16872aca8514c7c8c0a\n",
"Cool. This morning I tidied up a bit the wiki, mostly these two : added side page, improved a lot the home page.\n",
"Really like these changes, looks a lot nicer!\n\nOp wo 31 aug. 2016 om 14:30 schreef Brice Dutheil <notifications@github.com\n\n> :\n> \n> Cool. This morning I tidied up a bit the wiki, mostly these two : added\n> side page, improved a lot the home page.\n> \n> —\n> You are receiving this because you were mentioned.\n> Reply to this email directly, view it on GitHub\n> https://github.com/mockito/mockito/issues/596#issuecomment-243748893,\n> or mute the thread\n> https://github.com/notifications/unsubscribe-auth/AFrDb1nMLsk4jJe-dlo4-Z7zGUXM9e_Zks5qlXPagaJpZM4JsMzb\n> .\n",
"Guys, the \"What's new in Mockito 2\" is fantastic!!! Thanks a lot!\n",
"I like the \"What's new in Mockito 2\". I'm reviewing Mockito main javadoc. I might have some edits to the \"What's new\" wiki, will see :)\n",
"Yep sure ;)\n",
"@szczepiq I think we can close this issue since you reviewed Mockito class :P\n",
"I have some edits, hold on :) I'll finish by tomorrow!\n",
"Ok we ll monitor the check boxes ;)\n",
"@szczepiq Be sure to check out this wiki page as well. https://github.com/mockito/mockito/wiki/Mockito-Continuous-Delivery\n\nAnd fix or correct issues, I think this could be a starting point if you want to extract the _CDD_\n",
"> Move announcement / motivation text (https://github.com/mockito/mockito/blob/rc-release-notes-demo/doc/release-notes/official.md) to top of \"What's new in Mockito 2\"\n\nI would rather not do this since it clutters the content. That wikipage should be only about \"What's new in Mockito 2\", not what is upcoming in Mockito 3.\n\n> Final pass over \"What's new in Mockito 2\", make the information exciting and compelling, emphasize use cases, add missing links\n\nNot sure what you mean with \"exciting and compelling\" but I would rather not change the current text of the features. Let's keep it formal and clear.\n",
"@TimvdLippe migration guide does not mention two BDD enhancements I've developed: #212 and #311. I think it's worth sharing it with the world :)\n",
"@mkordas Yes definitely, I have added them!\n",
"@TimvdLippe thank you!\n",
"> I would rather not do this since it clutters the content. That wikipage should be only about \"What's new in Mockito 2\", not what is upcoming in Mockito 3.\n\nGood feedback. I'll think how to do it best.\n\n> Not sure what you mean with \"exciting and compelling\" but I would rather not change the current text of the features. Let's keep it formal and clear.\n\nBy compelling I mean ensuring that every feature describes the 'why' well enough (e.g., \"why should I care about the feature\"). Perhaps this requirement is already met. If that's the case, I don't need to make changes :)\n",
"Ah I didn't finish all I wanted :(. I'm pretty happy though. If someone else want's to pick up the work, go for it and pull the trigger :) Otherwise I can pick up the work tomorrow.\n\n@TimvdLippe, I considered your feedback about the 'what's new' page. Eventually, I went ahead and added introduction section. I hope it's ok ;) I added table of contents for people to quickly jump to improvements or incompatibilities. I didn't change much of the original text after all. It's well written. @bric3 , @TimvdLippe GREAT WORK!!!! You contributed not only great code but also great docs. Too many times I see that docs are not emphasized enough in software projects. Docs are part of the product and must be as high quality as code. Thanks for honoring this principle in Mockito.\n\nDamn, I'm proud of this release and you guys!!!!!!!!!! :)))))))))))))))))))))))))))))))))\n",
"The introduction looks good! Glad the wording of the changes remained\nfairly the same :)\n\nOn Thu, 8 Sep 2016, 06:55 Szczepan Faber, notifications@github.com wrote:\n\n> Ah I didn't finish all I wanted :(. I'm pretty happy though. If someone\n> else want's to pick up the work, go for it and pull the trigger :)\n> Otherwise I can pick up the work tomorrow.\n> \n> @TimvdLippe https://github.com/TimvdLippe, I considered your feedback\n> about the 'what's new' page. Eventually, I went ahead and added\n> introduction section. I hope it's ok ;) I added table of contents for\n> people to quickly jump to improvements or incompatibilities. I didn't\n> change much of the original text after all. It's well written. @bric3\n> https://github.com/bric3 , @TimvdLippe https://github.com/TimvdLippe\n> GREAT WORK!!!! You contributed not only great code but also great docs. Too\n> many times I see that docs are not emphasized enough in software projects.\n> Docs are part of the product and must be as high quality as code. Thanks\n> for honoring this principle in Mockito.\n> \n> Damn, I'm proud of this release and you guys!!!!!!!!!!\n> :)))))))))))))))))))))))))))))))))\n> \n> —\n> You are receiving this because you were mentioned.\n> Reply to this email directly, view it on GitHub\n> https://github.com/mockito/mockito/issues/596#issuecomment-245493487,\n> or mute the thread\n> https://github.com/notifications/unsubscribe-auth/AFrDb9MBUfxlvQ7_h2rI6y6cpZQ8a237ks5qn5UlgaJpZM4JsMzb\n> .\n",
"Made more progress. I didn't finish on time. My new ETA is weekend :) However, you don't need me to do the release :)\n",
"I'l just wait for #628 to be merged then I'll make this branch `release/2.x`\n",
"Woah, I'm done!\n\nT_H_A_N_K_S for patience and for pushing me & all of us to make progress on the release.\n"
] | [
"The href is incorrect and duplicated with [line 84](https://github.com/mockito/mockito/pull/628/files#diff-ddbc0d47e06a589778a6efe24c5d71d3R84)\n",
"well spotted. Thanks!\n"
] | "2016-09-09T05:30:37Z" | [] | Review and update documentation for 2.1.0 | - [x] update the migration guide (should be easy, there are not many breaking changes, if we miss out we can update in following RC)
- [x] add information about bytebuddy in the migration guide
- [x] mention noteworthy 2.0.0 features (should be easy, there are not many, plus they are already documented :)
- [x] fix odd TODO #593
- [x] review/update @since tags so that they say 2.1.0
Final steps I plan doing (by the EOD Wednesday, tomorrow), in order:
- [x] Test release from release/test (in progress, see Travis CI)
- [x] Merge/cherry-pick changes from "release/test" to master
- [x] Move announcement / motivation text (https://github.com/mockito/mockito/blob/rc-release-notes-demo/doc/release-notes/official.md) to top of "What's new in Mockito 2"
- [x] Final pass over "What's new in Mockito 2", make the information exciting and compelling, emphasize use cases, add missing links
- [x] Update the 2.1.0 information in main Mockito class to link to "What's new in Mockito 2". See "TODO 596" in code
- [x] Review Continuous Delivery [wiki page](https://github.com/mockito/mockito/wiki/Mockito-Continuous-Delivery)
- [x] Update the announcement text (https://github.com/mockito/mockito/blob/rc-release-notes-demo/doc/release-notes/official.md) so that instead of tons of text it just links to "What's new in Mockito 2"
- [x] Review release checklist (mostly done) - #620
- [x] Optional - Add some info in the 'What's new in Mockito 2' about the next steps for engs (e.g. ask to use the new version and give feedback).
| [
"src/main/java/org/mockito/Mockito.java"
] | [
"src/main/java/org/mockito/Mockito.java"
] | [] | diff --git a/src/main/java/org/mockito/Mockito.java b/src/main/java/org/mockito/Mockito.java
index 7baeea8cbe..92ca4cf668 100644
--- a/src/main/java/org/mockito/Mockito.java
+++ b/src/main/java/org/mockito/Mockito.java
@@ -30,7 +30,7 @@
* <h1>Contents</h1>
*
* <b>
- * <a href="#0">0. Migrating to 2.1.0</a><br/>
+ * <a href="#0">0. Migrating to Mockito 2</a><br/>
* <a href="#1">1. Let's verify some behaviour! </a><br/>
* <a href="#2">2. How about some stubbing? </a><br/>
* <a href="#3">3. Argument matchers </a><br/>
@@ -68,36 +68,25 @@
* <a href="#35">35. (new) Custom verification failure message (Since 2.1.0)</a><br/>
* <a href="#36">36. (new) Java 8 Lambda Matcher Support (Since 2.1.0)</a><br/>
* <a href="#37">37. (new) Java 8 Custom Answer Support (Since 2.1.0)</a><br/>
- *
* </b>
*
- * <h3 id="0">0. <a class="meaningful_link" href="#verification">Migrating to 2.1.0</a></h3>
+ * <h3 id="0">0. <a class="meaningful_link" href="#mockito2">Migrating to Mockito 2</a></h3>
*
* In order to continue improving Mockito and further improve the unit testing experience, we want you to upgrade to 2.1.0!
* Mockito follows <a href="http://semver.org/">semantic versioning</a>
* and contains breaking changes only on major version upgrades.
* In the lifecycle of a library, breaking changes are necessary
* to roll out a set of brand new features that alter the existing behavior or even change the API.
- * We hope that you enjoy Mockito 2.1.0!
- * <p>
- * List of breaking changes: TODO 596
- * <ul>
- * <li>Mockito is decoupled from Hamcrest and custom matchers API has changed, see {@link ArgumentMatcher}
- * for rationale and migration guide.</li>
- * <li>Stubbing API has been tweaked to avoid unavoidable compilation warnings that appeared on JDK7+ platform.
- * This will only affect binary compatibility, compilation compatibility remains unaffected.</li>
- * </ul>
+ * For comprehensive information about the new release including incompatible changes,
+ * see '<a href="https://github.com/mockito/mockito/wiki/What%27s-new-in-Mockito-2">What's new in Mockito 2</a>' wiki page.
+ * We hope that you enjoy Mockito 2!
+ *
+ * <h3 id="1">1. <a class="meaningful_link" href="#verification">Let's verify some behaviour!</a></h3>
*
- * <p>
* The following examples mock a List, because most people are familiar with the interface (such as the
* <code>add()</code>, <code>get()</code>, <code>clear()</code> methods). <br>
* In reality, please don't mock the List class. Use a real instance instead.
*
- *
- *
- *
- * <h3 id="1">1. <a class="meaningful_link" href="#verification">Let's verify some behaviour!</a></h3>
- *
* <pre class="code"><code class="java">
* //Let's import Mockito statically so that the code looks clearer
* import static org.mockito.Mockito.*;
| null | train | train | 2016-09-09T07:12:07 | "2016-08-24T16:28:24Z" | mockitoguy | train |
mockito/mockito/629_630 | mockito/mockito | mockito/mockito/629 | mockito/mockito/630 | [
"timestamp(timedelta=1.0, similarity=0.8787066601371085)",
"keyword_pr_to_issue"
] | 15cf2312df360f11282f3dec7915d4648e4ffb21 | 6003d4ec9625735acfd38782dd984f3817febc25 | [
"I don't had the problem when I tested the css the problem but that depend on the browser. \n\nIf you know how to fix it that would be awesome!\n",
"Just saw the PR thanks!\n",
"Probably after this change there will be still horizontal scroll-bar because I saw some other elements longer then 100% (with padding, margins and borders) . Even if they are - they will not be as significant as ones solved in PR.\n"
] | [] | "2016-09-09T20:36:42Z" | [] | Javadoc CSS width issue | There is some minor problem with element width (CSS) on javadoc site.
Some elements are too wide and are causing horizontal scroll bar to show up.
I post picture to show what is going on.
https://s9.postimg.io/xlbg2e0ul/mockito_javadoc.png
| [
"src/javadoc/stylesheet.css"
] | [
"src/javadoc/stylesheet.css"
] | [] | diff --git a/src/javadoc/stylesheet.css b/src/javadoc/stylesheet.css
index b33442208a..f4b3dd7fd5 100644
--- a/src/javadoc/stylesheet.css
+++ b/src/javadoc/stylesheet.css
@@ -246,15 +246,16 @@ Heading styles
ul.blockList ul.blockList li.blockList h3, ul.blockList ul.blockList li.blockList h3 {
background:#E0E6DF;
border:1px solid #C0C0C0;
- width: 110%;
- margin-left: -1em;
- padding-left: 1em;
+ width: 100%;
+ margin-left: 0;
+ padding-left: 0;
}
div.summary ul.blockList ul.blockList li.blockList h3 {
background:#E0E6DF;
- border:0;
- border:1px solid #C0C0C0;
- padding-left:5px;
+ border: 0 solid #C0C0C0;
+ padding: 0;
+ margin: 0;
+ width: 100%;
}
div.summary ul.blockList ul.blockList ul.blockList li.blockList h3 {
background:#E0E6DF;
| null | train | train | 2016-09-09T07:12:07 | "2016-09-09T20:16:23Z" | lukasz-szewc | train |
mockito/mockito/439_635 | mockito/mockito | mockito/mockito/439 | mockito/mockito/635 | [
"keyword_pr_to_issue"
] | 0fcad43a0a341fc4e3698c9b30faf377018b7b7e | 120d2204f8ebe68b5c3d6c3e587df40777a5a3a5 | [
"Yes `ArgumentCaptor` was not designed to be type aware. Though I like API with the least surprises, it should be fixed.\n\nThanks for reporting.\n",
"Note to my self: here is the solution [Gist ](https://gist.github.com/ChristianSchwarz/d755aa54e3637b0bd5f76bde3b882605)\n",
"This improvement makes Mockito easier to use and more intuitive. That's exactly the direction we should take Mockito. Thanks!!!\n"
] | [] | "2016-09-12T20:15:57Z" | [] | ArgumentCaptor and ArgumentMatcher can't be mixed in varargs | In the given test below the ArgumentCaptor should captor only the char 'c':
```
@Captor
private ArgumentCaptor<Character> argumentCaptor;
@Test
public void capturesVararg() throws Exception {
mock.varargs(42, 'c');
verify(mock).varargs(eq(42), argumentCaptor.capture());
assertThat(argumentCaptor.getAllValues()).containsExactly('c');
}
```
The test fails with this message:
```
Actual and expected should have same size but actual size was:
<2>
while expected size was:
<1>
Actual was:
<[42, 'c']>
Expected was:
<['c']>
```
Note that we see here 2 bugs:
- a wrong argument index was captored
- an `int`was captored by an `ArgumentCaptor<Character>` -> #565
| [
"src/main/java/org/mockito/internal/invocation/ArgumentsComparator.java",
"src/main/java/org/mockito/internal/invocation/InvocationMatcher.java"
] | [
"src/main/java/org/mockito/internal/invocation/ArgumentMatcherAction.java",
"src/main/java/org/mockito/internal/invocation/InvocationMatcher.java",
"src/main/java/org/mockito/internal/invocation/MatcherApplicationStrategy.java",
"src/main/java/org/mockito/internal/invocation/TypeSafeMatching.java"
] | [
"src/test/java/org/mockito/internal/invocation/MatcherApplicationStrategyTest.java",
"src/test/java/org/mockito/internal/invocation/TypeSafeMatchingTest.java",
"src/test/java/org/mockito/internal/util/reflection/FieldInitializerTest.java",
"src/test/java/org/mockitousage/matchers/VarargsTest.java"
] | diff --git a/src/main/java/org/mockito/internal/invocation/ArgumentMatcherAction.java b/src/main/java/org/mockito/internal/invocation/ArgumentMatcherAction.java
new file mode 100644
index 0000000000..29156d0b4c
--- /dev/null
+++ b/src/main/java/org/mockito/internal/invocation/ArgumentMatcherAction.java
@@ -0,0 +1,28 @@
+package org.mockito.internal.invocation;
+
+import org.mockito.ArgumentMatcher;
+
+public interface ArgumentMatcherAction {
+ /**
+ * Implementations must apply the given matcher to the argument and return
+ * <code>true</code> if the operation was successful or <code>false</code>
+ * if not. In this case no more matchers and arguments will be passed by
+ * {@link MatcherApplicationStrategy#forEachMatcherAndArgument(ArgumentMatcherAction)} to this method.
+ * .
+ *
+ * @param matcher
+ * to process the argument, never <code>null</code>
+ * @param argument
+ * to be processed by the matcher, can be <code>null</code>
+ * @return
+ * <ul>
+ * <li><code>true</code> if the <b>matcher</b> was successfully
+ * applied to the <b>argument</b> and the next pair of matcher and
+ * argument should be passed
+ * <li><code>false</code> otherwise
+ * </ul>
+ *
+ *
+ */
+ boolean apply(ArgumentMatcher<?> matcher, Object argument);
+}
diff --git a/src/main/java/org/mockito/internal/invocation/ArgumentsComparator.java b/src/main/java/org/mockito/internal/invocation/ArgumentsComparator.java
deleted file mode 100644
index 7b12fb2aff..0000000000
--- a/src/main/java/org/mockito/internal/invocation/ArgumentsComparator.java
+++ /dev/null
@@ -1,117 +0,0 @@
-/*
- * Copyright (c) 2007 Mockito contributors
- * This program is made available under the terms of the MIT License.
- */
-package org.mockito.internal.invocation;
-
-import java.lang.reflect.Method;
-import java.util.List;
-import org.mockito.ArgumentMatcher;
-import org.mockito.internal.matchers.VarargMatcher;
-import org.mockito.invocation.Invocation;
-
-@SuppressWarnings("unchecked")
-public class ArgumentsComparator {
-
- private ArgumentsComparator() {}
-
- public static boolean argumentsMatch(InvocationMatcher invocationMatcher, Invocation actual) {
- Object[] actualArgs = actual.getArguments();
- return argumentsMatch(invocationMatcher, actualArgs) || varArgsMatch(invocationMatcher, actual);
- }
-
- public static boolean argumentsMatch(InvocationMatcher invocationMatcher, Object[] actualArgs) {
- if (actualArgs.length != invocationMatcher.getMatchers().size()) {
- return false;
- }
- for (int i = 0; i < actualArgs.length; i++) {
- ArgumentMatcher<Object> argumentMatcher = invocationMatcher.getMatchers().get(i);
- Object argument = actualArgs[i];
-
- if (!matches(argumentMatcher, argument)) {
- return false;
- }
- }
- return true;
- }
-
- // ok, this method is a little bit messy but the vararg business unfortunately is messy...
- private static boolean varArgsMatch(InvocationMatcher invocationMatcher, Invocation actual) {
- if (!actual.getMethod().isVarArgs()) {
- // if the method is not vararg forget about it
- return false;
- }
-
- // we must use raw arguments, not arguments...
- Object[] rawArgs = actual.getRawArguments();
- List<ArgumentMatcher> matchers = invocationMatcher.getMatchers();
-
- if (rawArgs.length != matchers.size()) {
- return false;
- }
-
- for (int i = 0; i < rawArgs.length; i++) {
- ArgumentMatcher m = matchers.get(i);
- // it's a vararg because it's the last array in the arg list
- if (rawArgs[i] != null && rawArgs[i].getClass().isArray() && i == rawArgs.length - 1) {
- // this is very important to only allow VarargMatchers here. If
- // you're not sure why remove it and run all tests.
- if (!(m instanceof VarargMatcher) || !m.matches(rawArgs[i])) {
- return false;
- }
- // it's not a vararg (i.e. some ordinary argument before
- // varargs), just do the ordinary check
- } else if (!m.matches(rawArgs[i])) {
- return false;
- }
- }
-
- return true;
- }
-
- private static boolean matches(ArgumentMatcher<Object> argumentMatcher, Object argument) {
- return isCompatible(argumentMatcher, argument) && argumentMatcher.matches(argument);
- }
-
- /**
- * Returns <code>true</code> if the given <b>argument</b> can be passed to
- * the given <code>argumentMatcher</code> without causing a
- * {@link ClassCastException}.
- */
- private static boolean isCompatible(ArgumentMatcher<?> argumentMatcher, Object argument) {
- if (argument == null)
- return true;
-
- Class<?> expectedArgumentType = getArgumentType(argumentMatcher);
-
- return expectedArgumentType.isInstance(argument);
- }
-
- /**
- * Returns the type of {@link ArgumentMatcher#matches(Object)} of the given
- * {@link ArgumentMatcher} implementation.
- */
- private static Class<?> getArgumentType(ArgumentMatcher<?> argumentMatcher) {
- Method[] methods = argumentMatcher.getClass().getMethods();
- for (Method method : methods) {
- if (isMatchesMethod(method)) {
- return method.getParameterTypes()[0];
- }
- }
- throw new NoSuchMethodError("Method 'matches(T)' not found in ArgumentMatcher: " + argumentMatcher + " !\r\n Please file a bug with this stack trace at: https://github.com/mockito/mockito/issues/new ");
- }
-
- /**
- * Returns <code>true</code> if the given method is
- * {@link ArgumentMatcher#matches(Object)}
- */
- private static boolean isMatchesMethod(Method method) {
- if (method.getParameterTypes().length != 1) {
- return false;
- }
- if (method.isBridge()) {
- return false;
- }
- return method.getName().equals("matches");
- }
-}
diff --git a/src/main/java/org/mockito/internal/invocation/InvocationMatcher.java b/src/main/java/org/mockito/internal/invocation/InvocationMatcher.java
index 66ea8f5fbf..d955b70013 100644
--- a/src/main/java/org/mockito/internal/invocation/InvocationMatcher.java
+++ b/src/main/java/org/mockito/internal/invocation/InvocationMatcher.java
@@ -5,6 +5,15 @@
package org.mockito.internal.invocation;
+import static org.mockito.internal.invocation.ArgumentsProcessor.argumentsToMatchers;
+import static org.mockito.internal.invocation.MatcherApplicationStrategy.getMatcherApplicationStrategyFor;
+import static org.mockito.internal.invocation.TypeSafeMatching.matchesTypeSafe;
+
+import java.io.Serializable;
+import java.lang.reflect.Method;
+import java.util.Collections;
+import java.util.LinkedList;
+import java.util.List;
import org.mockito.ArgumentMatcher;
import org.mockito.internal.matchers.CapturesArguments;
import org.mockito.internal.reporting.PrintSettings;
@@ -12,36 +21,36 @@
import org.mockito.invocation.Invocation;
import org.mockito.invocation.Location;
-import static org.mockito.internal.invocation.ArgumentsComparator.argumentsMatch;
-
-import java.io.Serializable;
-import java.lang.reflect.Array;
-import java.lang.reflect.Method;
-import java.util.*;
-
-@SuppressWarnings("unchecked")
/**
- * In addition to all content of the invocation, the invocation matcher contains the argument matchers.
- * Invocation matcher is used during verification and stubbing.
- * In those cases, the user can provide argument matchers instead of 'raw' arguments.
- * Raw arguments are converted to 'equals' matchers anyway.
+ * In addition to all content of the invocation, the invocation matcher contains the argument matchers. Invocation matcher is used during verification and stubbing. In those cases, the user can provide argument matchers instead of 'raw' arguments. Raw arguments are converted to 'equals' matchers anyway.
*/
+@SuppressWarnings("serial")
public class InvocationMatcher implements DescribedInvocation, CapturesArgumentsFromInvocation, Serializable {
private final Invocation invocation;
- private final List<ArgumentMatcher> matchers;
+ private final List<ArgumentMatcher<?>> matchers;
+ @SuppressWarnings({ "rawtypes", "unchecked" })
public InvocationMatcher(Invocation invocation, List<ArgumentMatcher> matchers) {
this.invocation = invocation;
if (matchers.isEmpty()) {
- this.matchers = ArgumentsProcessor.argumentsToMatchers(invocation.getArguments());
+ this.matchers = (List) argumentsToMatchers(invocation.getArguments());
} else {
- this.matchers = matchers;
+ this.matchers = (List) matchers;
}
}
+ @SuppressWarnings("rawtypes")
public InvocationMatcher(Invocation invocation) {
- this(invocation, Collections.<ArgumentMatcher>emptyList());
+ this(invocation, Collections.<ArgumentMatcher> emptyList());
+ }
+
+ public static List<InvocationMatcher> createFrom(List<Invocation> invocations) {
+ LinkedList<InvocationMatcher> out = new LinkedList<InvocationMatcher>();
+ for (Invocation i : invocations) {
+ out.add(new InvocationMatcher(i));
+ }
+ return out;
}
public Method getMethod() {
@@ -49,54 +58,50 @@ public Method getMethod() {
}
public Invocation getInvocation() {
- return this.invocation;
+ return invocation;
}
+ @SuppressWarnings({ "unchecked", "rawtypes" })
public List<ArgumentMatcher> getMatchers() {
- return this.matchers;
+ return (List) matchers;
}
+ @Override
+ @SuppressWarnings({ "unchecked", "rawtypes" })
public String toString() {
- return new PrintSettings().print(matchers, invocation);
+ return new PrintSettings().print((List) matchers, invocation);
}
public boolean matches(Invocation actual) {
- return invocation.getMock().equals(actual.getMock())
- && hasSameMethod(actual)
- && argumentsMatch(this, actual);
- }
-
- private boolean safelyArgumentsMatch(Object[] actualArgs) {
- try {
- return argumentsMatch(this, actualArgs);
- } catch (Throwable t) {
- return false;
- }
+ return invocation.getMock().equals(actual.getMock()) && hasSameMethod(actual) && argumentsMatch(actual);
}
/**
- * similar means the same method name, same mock, unverified
- * and: if arguments are the same cannot be overloaded
+ * similar means the same method name, same mock, unverified and: if arguments are the same cannot be overloaded
*/
public boolean hasSimilarMethod(Invocation candidate) {
String wantedMethodName = getMethod().getName();
- String currentMethodName = candidate.getMethod().getName();
-
- final boolean methodNameEquals = wantedMethodName.equals(currentMethodName);
- final boolean isUnverified = !candidate.isVerified();
- final boolean mockIsTheSame = getInvocation().getMock() == candidate.getMock();
- final boolean methodEquals = hasSameMethod(candidate);
+ String candidateMethodName = candidate.getMethod().getName();
- if (!methodNameEquals || !isUnverified || !mockIsTheSame) {
+ if (!wantedMethodName.equals(candidateMethodName)) {
return false;
}
+ if (candidate.isVerified()) {
+ return false;
+ }
+ if (getInvocation().getMock() != candidate.getMock()) {
+ return false;
+ }
+ if (hasSameMethod(candidate)) {
+ return true;
+ }
- final boolean overloadedButSameArgs = !methodEquals && safelyArgumentsMatch(candidate.getArguments());
-
- return !overloadedButSameArgs;
+ return !argumentsMatch(candidate);
}
public boolean hasSameMethod(Invocation candidate) {
+ // not using method.equals() for 1 good reason:
+ // sometimes java generates forwarding methods when generics are in play see JavaGenericsForwardingMethodsTest
Method m1 = invocation.getMethod();
Method m2 = candidate.getMethod();
@@ -115,59 +120,34 @@ public boolean hasSameMethod(Invocation candidate) {
return false;
}
+ @Override
public Location getLocation() {
return invocation.getLocation();
}
+ @Override
public void captureArgumentsFrom(Invocation invocation) {
- captureRegularArguments(invocation);
- captureVarargsPart(invocation);
+ MatcherApplicationStrategy strategy = getMatcherApplicationStrategyFor(invocation, matchers);
+ strategy.forEachMatcherAndArgument(captureArgument());
}
- private void captureRegularArguments(Invocation invocation) {
- for (int position = 0; position < regularArgumentsSize(invocation); position++) {
- ArgumentMatcher m = matchers.get(position);
- if (m instanceof CapturesArguments) {
- ((CapturesArguments) m).captureFrom(invocation.getArgument(position));
- }
- }
- }
-
- private void captureVarargsPart(Invocation invocation) {
- if (!invocation.getMethod().isVarArgs()) {
- return;
- }
- int indexOfVararg = invocation.getRawArguments().length - 1;
- for (ArgumentMatcher m : uniqueMatcherSet(indexOfVararg)) {
- if (m instanceof CapturesArguments) {
- Object rawArgument = invocation.getRawArguments()[indexOfVararg];
- for (int i = 0; i < Array.getLength(rawArgument); i++) {
- ((CapturesArguments) m).captureFrom(Array.get(rawArgument, i));
+ private ArgumentMatcherAction captureArgument() {
+ return new ArgumentMatcherAction() {
+
+ @Override
+ public boolean apply(ArgumentMatcher<?> matcher, Object argument) {
+ if (matcher instanceof CapturesArguments) {
+ ((CapturesArguments) matcher).captureFrom(argument);
}
+
+ return true;
}
- }
- }
-
- private int regularArgumentsSize(Invocation invocation) {
- return invocation.getMethod().isVarArgs() ?
- invocation.getRawArguments().length - 1 // ignores vararg holder array
- : matchers.size();
- }
-
- private Set<ArgumentMatcher> uniqueMatcherSet(int indexOfVararg) {
- HashSet<ArgumentMatcher> set = new HashSet<ArgumentMatcher>();
- for (int position = indexOfVararg; position < matchers.size(); position++) {
- ArgumentMatcher matcher = matchers.get(position);
- set.add(matcher);
- }
- return set;
+ };
}
-
- public static List<InvocationMatcher> createFrom(List<Invocation> invocations) {
- LinkedList<InvocationMatcher> out = new LinkedList<InvocationMatcher>();
- for (Invocation i : invocations) {
- out.add(new InvocationMatcher(i));
- }
- return out;
+
+ @SuppressWarnings({ "rawtypes", "unchecked" })
+ private boolean argumentsMatch(Invocation actual) {
+ List matchers = getMatchers();
+ return getMatcherApplicationStrategyFor(actual, matchers).forEachMatcherAndArgument( matchesTypeSafe());
}
-}
+}
\ No newline at end of file
diff --git a/src/main/java/org/mockito/internal/invocation/MatcherApplicationStrategy.java b/src/main/java/org/mockito/internal/invocation/MatcherApplicationStrategy.java
new file mode 100644
index 0000000000..40c6519c91
--- /dev/null
+++ b/src/main/java/org/mockito/internal/invocation/MatcherApplicationStrategy.java
@@ -0,0 +1,128 @@
+package org.mockito.internal.invocation;
+
+import static org.mockito.internal.invocation.MatcherApplicationStrategy.MatcherApplicationType.ERROR_UNSUPPORTED_NUMBER_OF_MATCHERS;
+import static org.mockito.internal.invocation.MatcherApplicationStrategy.MatcherApplicationType.MATCH_EACH_VARARGS_WITH_LAST_MATCHER;
+import static org.mockito.internal.invocation.MatcherApplicationStrategy.MatcherApplicationType.ONE_MATCHER_PER_ARGUMENT;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.mockito.ArgumentMatcher;
+import org.mockito.internal.matchers.CapturingMatcher;
+import org.mockito.internal.matchers.VarargMatcher;
+import org.mockito.invocation.Invocation;
+
+public class MatcherApplicationStrategy {
+
+ private final Invocation invocation;
+ private final List<ArgumentMatcher<?>> matchers;
+ private final MatcherApplicationType matchingType;
+
+
+
+ private MatcherApplicationStrategy(Invocation invocation, List<ArgumentMatcher<?>> matchers, MatcherApplicationType matchingType) {
+ this.invocation = invocation;
+ if (matchingType == MATCH_EACH_VARARGS_WITH_LAST_MATCHER) {
+ int times = varargLength(invocation);
+ this.matchers = appendLastMatcherNTimes(matchers, times);
+ } else {
+ this.matchers = matchers;
+ }
+
+ this.matchingType = matchingType;
+ }
+
+ /**
+ * Returns the {@link MatcherApplicationStrategy} that must be used to capture the
+ * arguments of the given <b>invocation</b> using the given <b>matchers</b>.
+ *
+ * @param invocation
+ * that contain the arguments to capture
+ * @param matchers
+ * that will be used to capture the arguments of the invocation,
+ * the passed {@link List} is not required to contain a
+ * {@link CapturingMatcher}
+ * @return never <code>null</code>
+ */
+ public static MatcherApplicationStrategy getMatcherApplicationStrategyFor(Invocation invocation, List<ArgumentMatcher<?>> matchers) {
+
+ MatcherApplicationType type = getMatcherApplicationType(invocation, matchers);
+ return new MatcherApplicationStrategy(invocation, matchers, type);
+ }
+
+ /**
+ * Applies the given {@link ArgumentMatcherAction} to all arguments and
+ * corresponding matchers
+ *
+ * @param action
+ * must not be <code>null</code>
+ * @return
+ * <ul>
+ * <li><code>true</code> if the given <b>action</b> returned
+ * <code>true</code> for all arguments and matchers passed to it.
+ * <li><code>false</code> if the given <b>action</b> returned
+ * <code>false</code> for one of the passed arguments and matchers
+ * <li><code>false</code> if the given matchers don't fit to the given invocation
+ * because too many or to few matchers are available.
+ * </ul>
+ */
+ public boolean forEachMatcherAndArgument(ArgumentMatcherAction action) {
+ if (matchingType == ERROR_UNSUPPORTED_NUMBER_OF_MATCHERS)
+ return false;
+
+ Object[] arguments = invocation.getArguments();
+ for (int i = 0; i < arguments.length; i++) {
+ ArgumentMatcher<?> matcher = matchers.get(i);
+ Object argument = arguments[i];
+
+ if (!action.apply(matcher, argument)) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ private static MatcherApplicationType getMatcherApplicationType(Invocation invocation, List<ArgumentMatcher<?>> matchers) {
+ final int rawArguments = invocation.getRawArguments().length;
+ final int expandedArguments = invocation.getArguments().length;
+ final int matcherCount = matchers.size();
+
+ if (expandedArguments == matcherCount) {
+ return ONE_MATCHER_PER_ARGUMENT;
+ }
+
+ if (rawArguments == matcherCount && isLastMatcherVargargMatcher(matchers)) {
+ return MATCH_EACH_VARARGS_WITH_LAST_MATCHER;
+ }
+
+ return ERROR_UNSUPPORTED_NUMBER_OF_MATCHERS;
+ }
+
+ private static boolean isLastMatcherVargargMatcher(final List<ArgumentMatcher<?>> matchers) {
+ return lastMatcher(matchers) instanceof VarargMatcher;
+ }
+
+ private static List<ArgumentMatcher<?>> appendLastMatcherNTimes(List<ArgumentMatcher<?>> matchers, int timesToAppendLastMatcher) {
+ ArgumentMatcher<?> lastMatcher = lastMatcher(matchers);
+
+ List<ArgumentMatcher<?>> expandedMatchers = new ArrayList<ArgumentMatcher<?>>(matchers);
+ for (int i = 0; i < timesToAppendLastMatcher; i++) {
+ expandedMatchers.add(lastMatcher);
+ }
+ return expandedMatchers;
+ }
+
+ private static int varargLength(Invocation invocation) {
+ int rawArgumentCount = invocation.getRawArguments().length;
+ int expandedArgumentCount = invocation.getArguments().length;
+ return expandedArgumentCount - rawArgumentCount;
+ }
+
+ private static ArgumentMatcher<?> lastMatcher(List<ArgumentMatcher<?>> matchers) {
+ return matchers.get(matchers.size() - 1);
+ }
+
+ enum MatcherApplicationType {
+ ONE_MATCHER_PER_ARGUMENT, MATCH_EACH_VARARGS_WITH_LAST_MATCHER, ERROR_UNSUPPORTED_NUMBER_OF_MATCHERS;
+ }
+}
\ No newline at end of file
diff --git a/src/main/java/org/mockito/internal/invocation/TypeSafeMatching.java b/src/main/java/org/mockito/internal/invocation/TypeSafeMatching.java
new file mode 100644
index 0000000000..181e47fea9
--- /dev/null
+++ b/src/main/java/org/mockito/internal/invocation/TypeSafeMatching.java
@@ -0,0 +1,70 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.invocation;
+
+import java.lang.reflect.Method;
+
+import org.mockito.ArgumentMatcher;
+
+@SuppressWarnings({"unchecked","rawtypes"})
+public class TypeSafeMatching implements ArgumentMatcherAction {
+
+ private final static ArgumentMatcherAction TYPE_SAFE_MATCHING_ACTION = new TypeSafeMatching();
+
+ private TypeSafeMatching() {}
+
+
+ public static ArgumentMatcherAction matchesTypeSafe(){
+ return TYPE_SAFE_MATCHING_ACTION;
+ }
+ @Override
+ public boolean apply(ArgumentMatcher matcher, Object argument) {
+ return isCompatible(matcher, argument) && matcher.matches(argument);
+ }
+
+
+ /**
+ * Returns <code>true</code> if the given <b>argument</b> can be passed to
+ * the given <code>argumentMatcher</code> without causing a
+ * {@link ClassCastException}.
+ */
+ private static boolean isCompatible(ArgumentMatcher<?> argumentMatcher, Object argument) {
+ if (argument == null)
+ return true;
+
+ Class<?> expectedArgumentType = getArgumentType(argumentMatcher);
+
+ return expectedArgumentType.isInstance(argument);
+ }
+
+ /**
+ * Returns the type of {@link ArgumentMatcher#matches(Object)} of the given
+ * {@link ArgumentMatcher} implementation.
+ */
+ private static Class<?> getArgumentType(ArgumentMatcher<?> argumentMatcher) {
+ Method[] methods = argumentMatcher.getClass().getMethods();
+
+ for (Method method : methods) {
+ if (isMatchesMethod(method)) {
+ return method.getParameterTypes()[0];
+ }
+ }
+ throw new NoSuchMethodError("Method 'matches(T)' not found in ArgumentMatcher: " + argumentMatcher + " !\r\n Please file a bug with this stack trace at: https://github.com/mockito/mockito/issues/new ");
+ }
+
+ /**
+ * Returns <code>true</code> if the given method is
+ * {@link ArgumentMatcher#matches(Object)}
+ */
+ private static boolean isMatchesMethod(Method method) {
+ if (method.getParameterTypes().length != 1) {
+ return false;
+ }
+ if (method.isBridge()) {
+ return false;
+ }
+ return method.getName().equals("matches");
+ }
+}
\ No newline at end of file
| diff --git a/src/test/java/org/mockito/internal/invocation/ArgumentsComparatorTest.java b/src/test/java/org/mockito/internal/invocation/ArgumentsComparatorTest.java
deleted file mode 100644
index 9aed7c77e7..0000000000
--- a/src/test/java/org/mockito/internal/invocation/ArgumentsComparatorTest.java
+++ /dev/null
@@ -1,205 +0,0 @@
-/*
- * Copyright (c) 2007 Mockito contributors
- * This program is made available under the terms of the MIT License.
- */
-package org.mockito.internal.invocation;
-
-import static java.util.Arrays.asList;
-import static junit.framework.TestCase.assertFalse;
-import static junit.framework.TestCase.assertTrue;
-import static org.mockito.internal.invocation.ArgumentsComparator.argumentsMatch;
-import static org.mockito.internal.matchers.Any.ANY;
-
-import java.util.List;
-import org.junit.Test;
-import org.mockito.Mock;
-import org.mockito.internal.matchers.Any;
-import org.mockito.internal.matchers.Equals;
-import org.mockito.internal.matchers.InstanceOf;
-import org.mockito.invocation.Invocation;
-import org.mockitousage.IMethods;
-import org.mockitoutil.TestBase;
-
-@SuppressWarnings("unchecked")
-public class ArgumentsComparatorTest extends TestBase {
-
- @Mock IMethods mock;
-
- @Test
- public void shouldKnowWhenArgumentsMatch() {
- //given
- Invocation invocation = new InvocationBuilder().args("1", 100).toInvocation();
- InvocationMatcher invocationMatcher = new InvocationBuilder().args("1", 100).toInvocationMatcher();
-
- //when
- boolean match = argumentsMatch(invocationMatcher, invocation);
-
- //then
- assertTrue(match);
- }
-
- @Test
- public void shouldKnowWhenArgsDifferent() {
- //given
- Invocation invocation = new InvocationBuilder().args("1", 100).toInvocation();
- InvocationMatcher invocationMatcher = new InvocationBuilder().args("100", 100).toInvocationMatcher();
-
- //when
- boolean match = argumentsMatch(invocationMatcher, invocation);
-
- //then
- assertFalse(match);
- }
-
- @Test
- public void shouldKnowWhenActualArgsSizeIsDifferent() {
- //given
- Invocation invocation = new InvocationBuilder().args("100", 100).toInvocation();
- InvocationMatcher invocationMatcher = new InvocationBuilder().args("100").toInvocationMatcher();
-
- //when
- boolean match = argumentsMatch(invocationMatcher, invocation);
-
- //then
- assertFalse(match);
- }
-
- @Test
- public void shouldKnowWhenMatchersSizeIsDifferent() {
- //given
- Invocation invocation = new InvocationBuilder().args("100").toInvocation();
- InvocationMatcher invocationMatcher = new InvocationBuilder().args("100", 100).toInvocationMatcher();
-
- //when
- boolean match = argumentsMatch(invocationMatcher, invocation);
-
- //then
- assertFalse(match);
- }
-
- @Test
- public void shouldKnowWhenVarargsMatch() {
- //given
- mock.varargs("1", "2", "3");
- Invocation invocation = getLastInvocation();
- InvocationMatcher invocationMatcher = new InvocationMatcher(invocation, (List) asList(new Equals("1"), Any.ANY, new InstanceOf(String.class)));
-
- //when
- boolean match = argumentsMatch(invocationMatcher, invocation);
-
- //then
- assertTrue(match);
- }
-
- @Test
- public void shouldKnowWhenVarargsDifferent() {
- //given
- mock.varargs("1", "2");
- Invocation invocation = getLastInvocation();
- InvocationMatcher invocationMatcher = new InvocationMatcher(invocation, (List) asList(new Equals("100"), Any.ANY));
-
- //when
- boolean match = argumentsMatch(invocationMatcher, invocation);
-
- //then
- assertFalse(match);
- }
-
- @Test
- public void shouldAllowAnyVarargMatchEntireVararg() {
- //given
- mock.varargs("1", "2");
- Invocation invocation = getLastInvocation();
- InvocationMatcher invocationMatcher = new InvocationMatcher(invocation, (List) asList(ANY));
-
- //when
- boolean match = argumentsMatch(invocationMatcher, invocation);
-
- //then
- assertTrue(match);
- }
-
- @Test
- public void shouldNotAllowAnyObjectWithMixedVarargs() {
- //given
- mock.mixedVarargs(1, "1", "2");
- Invocation invocation = getLastInvocation();
- InvocationMatcher invocationMatcher = new InvocationMatcher(invocation, (List) asList(new Equals(1)));
-
- //when
- boolean match = argumentsMatch(invocationMatcher, invocation);
-
- //then
- assertFalse(match);
- }
-
- @Test
- public void shouldAllowAnyObjectWithMixedVarargs() {
- //given
- mock.mixedVarargs(1, "1", "2");
- Invocation invocation = getLastInvocation();
- InvocationMatcher invocationMatcher = new InvocationMatcher(invocation, (List) asList(new Equals(1), ANY));
-
- //when
- boolean match = argumentsMatch(invocationMatcher, invocation);
-
- //then
- assertTrue(match);
- }
-
- @Test
- public void shouldNotMatchWhenSomeOtherArgumentDoesNotMatch() {
- //given
- mock.mixedVarargs(1, "1", "2");
- Invocation invocation = getLastInvocation();
- InvocationMatcher invocationMatcher = new InvocationMatcher(invocation, (List) asList(new Equals(100), ANY));
-
- //when
- boolean match = argumentsMatch(invocationMatcher, invocation);
-
- //then
- assertFalse(match);
- }
-
- @Test
- public void shouldAnyObjectVarargDealWithDifferentSizeOfArgs() {
- //given
- mock.mixedVarargs(1, "1", "2");
- Invocation invocation = getLastInvocation();
- InvocationMatcher invocationMatcher = new InvocationMatcher(invocation, (List) asList(new Equals(1)));
-
- //when
- boolean match = argumentsMatch(invocationMatcher, invocation);
-
- //then
- assertFalse(match);
- }
-
- @Test
- public void shouldMatchAnyVarargEvenIfOneOfTheArgsIsNull() {
- //given
- mock.mixedVarargs(null, null, "2");
- Invocation invocation = getLastInvocation();
- InvocationMatcher invocationMatcher = new InvocationMatcher(invocation, (List) asList(new Equals(null), ANY));
-
- //when
- boolean match = argumentsMatch(invocationMatcher, invocation);
-
- //then
- assertTrue(match);
- }
-
- @Test
- public void shouldMatchAnyVarargEvenIfMatcherIsDecorated() {
- //given
- mock.varargs("1", "2");
- Invocation invocation = getLastInvocation();
- InvocationMatcher invocationMatcher = new InvocationMatcher(invocation, (List)asList(ANY));
-
- //when
- boolean match = argumentsMatch(invocationMatcher, invocation);
-
- //then
- assertTrue(match);
- }
-}
\ No newline at end of file
diff --git a/src/test/java/org/mockito/internal/invocation/MatcherApplicationStrategyTest.java b/src/test/java/org/mockito/internal/invocation/MatcherApplicationStrategyTest.java
new file mode 100644
index 0000000000..6a0c6c696e
--- /dev/null
+++ b/src/test/java/org/mockito/internal/invocation/MatcherApplicationStrategyTest.java
@@ -0,0 +1,231 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.invocation;
+
+import static java.util.Arrays.asList;
+import static junit.framework.TestCase.assertFalse;
+import static junit.framework.TestCase.assertTrue;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.internal.invocation.MatcherApplicationStrategy.getMatcherApplicationStrategyFor;
+import static org.mockito.internal.matchers.Any.ANY;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.ArgumentMatcher;
+import org.mockito.Mock;
+import org.mockito.internal.matchers.Any;
+import org.mockito.internal.matchers.Equals;
+import org.mockito.internal.matchers.InstanceOf;
+import org.mockito.invocation.Invocation;
+import org.mockitousage.IMethods;
+import org.mockitoutil.TestBase;
+
+@SuppressWarnings("unchecked")
+public class MatcherApplicationStrategyTest extends TestBase {
+
+ @Mock
+ IMethods mock;
+ private Invocation invocation;
+ private List matchers;
+
+ private RecordingAction recordAction;
+
+ @Before
+ public void before() {
+ recordAction = new RecordingAction();
+ }
+
+ @Test
+ public void shouldKnowWhenActualArgsSizeIsDifferent1() {
+ // given
+ invocation = varargs("1");
+ matchers = asList(new Equals("1"));
+
+ // when
+ boolean match = getMatcherApplicationStrategyFor(invocation, matchers).forEachMatcherAndArgument(RETURN_ALWAYS_FALSE);
+
+ // then
+ assertFalse(match);
+ }
+
+ @Test
+ public void shouldKnowWhenActualArgsSizeIsDifferent2() {
+ // given
+ invocation = varargs("1");
+ matchers = asList(new Equals("1"));
+
+ // when
+ boolean match = getMatcherApplicationStrategyFor(invocation, matchers).forEachMatcherAndArgument(RETURN_ALWAYS_TRUE);
+
+ // then
+ assertTrue(match);
+ }
+
+ @Test
+ public void shouldKnowWhenActualArgsSizeIsDifferent() {
+ // given
+ invocation = varargs("1", "2");
+ matchers = asList(new Equals("1"));
+
+ // when
+ boolean match = getMatcherApplicationStrategyFor(invocation, matchers).forEachMatcherAndArgument(RETURN_ALWAYS_TRUE);
+
+ // then
+ assertFalse(match);
+ }
+
+ @Test
+ public void shouldKnowWhenMatchersSizeIsDifferent() {
+ // given
+ invocation = varargs("1");
+ matchers = asList(new Equals("1"), new Equals("2"));
+
+ // when
+ boolean match = getMatcherApplicationStrategyFor(invocation, matchers).forEachMatcherAndArgument(RETURN_ALWAYS_TRUE);
+
+ // then
+ assertFalse(match);
+ }
+
+ @Test
+ public void shouldKnowWhenVarargsMatch() {
+ // given
+ invocation = varargs("1", "2", "3");
+ matchers = asList(new Equals("1"), Any.ANY, new InstanceOf(String.class));
+
+ // when
+ boolean match = getMatcherApplicationStrategyFor(invocation, matchers).forEachMatcherAndArgument(recordAction);
+
+ // then
+ assertTrue(match);
+ }
+
+ @Test
+ public void shouldAllowAnyVarargMatchEntireVararg() {
+ // given
+ invocation = varargs("1", "2");
+ matchers = asList(ANY);
+
+ // when
+ boolean match = getMatcherApplicationStrategyFor(invocation, matchers).forEachMatcherAndArgument(recordAction);
+
+ // then
+ assertTrue(match);
+ }
+
+ @Test
+ public void shouldNotAllowAnyObjectWithMixedVarargs() {
+ // given
+ invocation = mixedVarargs(1, "1", "2");
+ matchers = asList(new Equals(1));
+
+ // when
+ boolean match = getMatcherApplicationStrategyFor(invocation, matchers).forEachMatcherAndArgument(recordAction);
+
+ // then
+ assertFalse(match);
+ }
+
+ @Test
+ public void shouldAllowAnyObjectWithMixedVarargs() {
+ // given
+ invocation = mixedVarargs(1, "1", "2");
+ matchers = asList(new Equals(1), ANY);
+
+ // when
+ boolean match = getMatcherApplicationStrategyFor(invocation, matchers).forEachMatcherAndArgument(recordAction);
+
+ // then
+ assertTrue(match);
+ }
+
+ @Test
+ public void shouldAnyObjectVarargDealWithDifferentSizeOfArgs() {
+ // given
+ invocation = mixedVarargs(1, "1", "2");
+ matchers = asList(new Equals(1));
+
+ // when
+ boolean match = getMatcherApplicationStrategyFor(invocation, matchers).forEachMatcherAndArgument(recordAction);
+
+ // then
+ assertFalse(match);
+
+ recordAction.assertIsEmpty();
+ }
+
+ @Test
+ public void shouldMatchAnyVarargEvenIfOneOfTheArgsIsNull() {
+ // given
+ invocation = mixedVarargs(null, null, "2");
+ matchers = asList(new Equals(null), ANY);
+
+ // when
+ getMatcherApplicationStrategyFor(invocation, matchers).forEachMatcherAndArgument(recordAction);
+
+ // then
+ recordAction.assertContainsExactly(new Equals(null), ANY, ANY);
+
+ }
+
+ @Test
+ public void shouldMatchAnyVarargEvenIfMatcherIsDecorated() {
+ // given
+ invocation = varargs("1", "2");
+ matchers = asList(ANY);
+
+ // when
+ getMatcherApplicationStrategyFor(invocation, matchers).forEachMatcherAndArgument(recordAction);
+
+ // then
+ recordAction.assertContainsExactly(ANY, ANY);
+ }
+
+ private Invocation mixedVarargs(Object a, String... s) {
+ mock.mixedVarargs(a, s);
+ return getLastInvocation();
+ }
+
+ private Invocation varargs(String... s) {
+ mock.varargs(s);
+ return getLastInvocation();
+ }
+
+ private class RecordingAction implements ArgumentMatcherAction {
+ private List<ArgumentMatcher<?>> matchers = new ArrayList<ArgumentMatcher<?>>();
+
+ @Override
+ public boolean apply(ArgumentMatcher<?> matcher, Object argument) {
+ matchers.add(matcher);
+ return true;
+ }
+
+ public void assertIsEmpty() {
+ assertThat(matchers).isEmpty();
+ }
+
+ public void assertContainsExactly(ArgumentMatcher<?>... matchers) {
+ assertThat(this.matchers).containsExactly(matchers);
+ }
+ }
+
+ private static final ArgumentMatcherAction RETURN_ALWAYS_TRUE = new ArgumentMatcherAction() {
+ @Override
+ public boolean apply(ArgumentMatcher<?> matcher, Object argument) {
+ return true;
+ }
+ };
+
+ private static final ArgumentMatcherAction RETURN_ALWAYS_FALSE = new ArgumentMatcherAction() {
+ @Override
+ public boolean apply(ArgumentMatcher<?> matcher, Object argument) {
+ return false;
+ }
+ };
+
+}
\ No newline at end of file
diff --git a/src/test/java/org/mockito/internal/invocation/TypeSafeMatchingTest.java b/src/test/java/org/mockito/internal/invocation/TypeSafeMatchingTest.java
new file mode 100644
index 0000000000..39deb6796f
--- /dev/null
+++ b/src/test/java/org/mockito/internal/invocation/TypeSafeMatchingTest.java
@@ -0,0 +1,163 @@
+package org.mockito.internal.invocation;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.internal.invocation.TypeSafeMatching.matchesTypeSafe;
+
+import java.util.Date;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import org.junit.Rule;
+import org.junit.Test;
+import org.mockito.ArgumentMatcher;
+import org.mockito.Mock;
+import org.mockito.internal.matchers.LessOrEqual;
+import org.mockito.internal.matchers.Null;
+import org.mockito.internal.matchers.StartsWith;
+import org.mockito.junit.MockitoJUnit;
+import org.mockito.junit.MockitoRule;
+import org.mockitousage.IMethods;
+
+public class TypeSafeMatchingTest {
+
+ private static final Object NOT_A_COMPARABLE = new Object();
+
+ @Rule
+ public MockitoRule mockitoRule = MockitoJUnit.rule();
+
+ @Mock
+ public IMethods mock;
+
+ /**
+ * Should not throw an {@link NullPointerException}
+ *
+ * @see Bug-ID https://github.com/mockito/mockito/issues/457
+ */
+ @Test
+ public void compareNullArgument() {
+ boolean match = matchesTypeSafe().apply(new LessOrEqual<Integer>(5), null);
+ assertThat(match).isFalse();
+
+ }
+
+ /**
+ * Should not throw an {@link ClassCastException}
+ */
+ @Test
+ public void compareToNonCompareable() {
+ boolean match = matchesTypeSafe().apply(new LessOrEqual<Integer>(5), NOT_A_COMPARABLE);
+ assertThat(match).isFalse();
+ }
+
+ /**
+ * Should not throw an {@link ClassCastException}
+ */
+ @Test
+ public void compareToNull() {
+ boolean match = matchesTypeSafe().apply(new LessOrEqual<Integer>(null), null);
+ assertThat(match).isFalse();
+ }
+
+ /**
+ * Should not throw an {@link ClassCastException}
+ */
+ @Test
+ public void compareToNull2() {
+ boolean match = matchesTypeSafe().apply(Null.NULL, null);
+ assertThat(match).isTrue();
+ }
+
+ /**
+ * Should not throw an {@link ClassCastException}
+ */
+ @Test
+ public void compareToStringVsInt() {
+ boolean match = matchesTypeSafe().apply(new StartsWith("Hello"), 123);
+ assertThat(match).isFalse();
+ }
+
+ @Test
+ public void compareToIntVsString() throws Exception {
+ boolean match = matchesTypeSafe().apply(new LessOrEqual<Integer>(5), "Hello");
+ assertThat(match).isFalse();
+ }
+
+ @Test
+ public void matchesOverloadsMustBeIgnored() {
+ class TestMatcher implements ArgumentMatcher<Integer> {
+ @Override
+ public boolean matches(Integer arg) {
+ return false;
+ }
+
+ @SuppressWarnings("unused")
+ public boolean matches(Date arg) {
+ throw new UnsupportedOperationException();
+ }
+
+ @SuppressWarnings("unused")
+ public boolean matches(Integer arg, Void v) {
+ throw new UnsupportedOperationException();
+ }
+
+ }
+
+ boolean match = matchesTypeSafe().apply(new TestMatcher(), 123);
+ assertThat(match).isFalse();
+ }
+
+ @Test
+ public void matchesWithSubTypeExtendingGenericClass() {
+ abstract class GenericMatcher<T> implements ArgumentMatcher<T> {
+ }
+ class TestMatcher extends GenericMatcher<Integer> {
+ @Override
+ public boolean matches(Integer argument) {
+ return true;
+ }
+ }
+ boolean match = matchesTypeSafe().apply(new TestMatcher(), 123);
+ assertThat(match).isTrue();
+ }
+
+ @Test
+ public void dontMatchesWithSubTypeExtendingGenericClass() {
+ final AtomicBoolean wasCalled = new AtomicBoolean();
+
+ abstract class GenericMatcher<T> implements ArgumentMatcher<T> {
+ }
+ class TestMatcher extends GenericMatcher<Integer> {
+ @Override
+ public boolean matches(Integer argument) {
+ wasCalled.set(true);
+ return true;
+ }
+ }
+ wasCalled.set(false);
+ matchesTypeSafe().apply(new TestMatcher(), 123);
+ assertThat(wasCalled.get()).isTrue();
+
+ wasCalled.set(false);
+ matchesTypeSafe().apply(new TestMatcher(), "");
+ assertThat(wasCalled.get()).isFalse();
+ }
+
+ @Test
+ public void passEveryArgumentTypeIfNoBridgeMethodWasGenerated() {
+ final AtomicBoolean wasCalled = new AtomicBoolean();
+ class GenericMatcher<T> implements ArgumentMatcher<T> {
+ @Override
+ public boolean matches(T argument) {
+ wasCalled.set(true);
+ return true;
+ }
+ }
+
+ wasCalled.set(false);
+ matchesTypeSafe().apply(new GenericMatcher<Integer>(), 123);
+ assertThat(wasCalled.get()).isTrue();
+
+ wasCalled.set(false);
+ matchesTypeSafe().apply(new GenericMatcher<Integer>(), "");
+ assertThat(wasCalled.get()).isTrue();
+ }
+}
diff --git a/src/test/java/org/mockito/internal/util/reflection/FieldInitializerTest.java b/src/test/java/org/mockito/internal/util/reflection/FieldInitializerTest.java
index 38cafecc82..185bfaea17 100644
--- a/src/test/java/org/mockito/internal/util/reflection/FieldInitializerTest.java
+++ b/src/test/java/org/mockito/internal/util/reflection/FieldInitializerTest.java
@@ -6,6 +6,7 @@
import org.junit.Test;
import org.mockito.InjectMocks;
+import org.mockito.Mockito;
import org.mockito.exceptions.base.MockitoException;
import org.mockito.internal.util.reflection.FieldInitializer.ConstructorArgumentResolver;
@@ -156,7 +157,7 @@ public void should_not_fail_if_inner_class_field_is_instantiated() throws Except
@Test
public void can_instantiate_class_with_parameterized_constructor() throws Exception {
- ConstructorArgumentResolver resolver = given(mock(ConstructorArgumentResolver.class).resolveTypeInstances(any(Class[].class)))
+ ConstructorArgumentResolver resolver = given(mock(ConstructorArgumentResolver.class).resolveTypeInstances(any(Class.class)))
.willReturn(new Object[]{null}).getMock();
new FieldInitializer(this, field("noDefaultConstructor"), resolver).initialize();
diff --git a/src/test/java/org/mockitousage/matchers/VarargsTest.java b/src/test/java/org/mockitousage/matchers/VarargsTest.java
new file mode 100644
index 0000000000..6720ca5ff0
--- /dev/null
+++ b/src/test/java/org/mockitousage/matchers/VarargsTest.java
@@ -0,0 +1,341 @@
+package org.mockitousage.matchers;
+
+import static org.junit.Assert.fail;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.ArgumentMatchers.isNotNull;
+import static org.mockito.ArgumentMatchers.isNull;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import org.assertj.core.api.AbstractListAssert;
+import org.assertj.core.api.Assertions;
+import org.assertj.core.api.Condition;
+import org.junit.Ignore;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.ExpectedException;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Captor;
+import org.mockito.Mock;
+import org.mockito.exceptions.verification.junit.ArgumentsAreDifferent;
+import org.mockito.junit.MockitoJUnit;
+import org.mockito.junit.MockitoRule;
+import org.mockitousage.IMethods;
+
+public class VarargsTest {
+
+ @Rule
+ public MockitoRule mockitoRule = MockitoJUnit.rule();
+ @Rule
+ public ExpectedException exception = ExpectedException.none();
+ @Captor
+ private ArgumentCaptor<String> captor;
+ @Mock
+ private IMethods mock;
+
+ private static final Condition<Object> NULL = new Condition<Object>() {
+
+ @Override
+ public boolean matches(Object value) {
+ return value == null;
+ }
+ };
+
+ @Test
+ public void shouldMatchVarArgs_noArgs() {
+ mock.varargs();
+
+ verify(mock).varargs();
+ }
+
+ @Test
+ @Ignore("This test must succeed but is fails currently, see github issue #616")
+ public void shouldMatchEmptyVarArgs_noArgsIsNotNull() {
+ mock.varargs();
+
+ verify(mock).varargs(isNotNull());
+ }
+
+ @Test
+ @Ignore("This test must succeed but is fails currently, see github issue #616")
+ public void shouldMatchEmptyVarArgs_noArgsIsNull() {
+ mock.varargs();
+
+ verify(mock).varargs(isNull());
+ }
+
+ @Test
+ @Ignore("This test must succeed but is fails currently, see github issue #616")
+ public void shouldMatchEmptyVarArgs_noArgsIsNotNullArray() {
+ mock.varargs();
+
+ verify(mock).varargs((String[]) isNotNull());
+ }
+
+ @Test
+ public void shouldMatchVarArgs_oneNullArg_eqNull() {
+ Object arg = null;
+ mock.varargs(arg);
+
+ verify(mock).varargs(eq(null));
+ }
+
+ @Test
+ public void shouldMatchVarArgs_oneNullArg_isNull() {
+ Object arg = null;
+ mock.varargs(arg);
+
+ verify(mock).varargs(isNull());
+ }
+
+ @Test
+ public void shouldMatchVarArgs_nullArrayArg() {
+ Object[] argArray = null;
+ mock.varargs(argArray);
+
+ verify(mock).varargs(isNull());
+ }
+
+ @Test
+ public void shouldnotMatchVarArgs_twoArgsOneMatcher() {
+ mock.varargs("1", "1");
+
+ exception.expectMessage("Argument(s) are different");
+
+ verify(mock).varargs(eq("1"));
+ }
+
+ @Test
+ public void shouldMatchVarArgs_emptyVarArgsOneAnyMatcher() {
+ mock.varargs();
+
+ verify(mock).varargs((String[])any()); // any() -> VarargMatcher
+ }
+
+ @Test
+ public void shouldMatchVarArgs_oneArgsOneAnyMatcher() {
+ mock.varargs(1);
+
+ verify(mock).varargs(any()); // any() -> VarargMatcher
+ }
+
+ @Test
+ public void shouldMatchVarArgs_twoArgsOneAnyMatcher() {
+ mock.varargs(1, 2);
+
+ verify(mock).varargs(any()); // any() -> VarargMatcher
+ }
+
+ @Test
+ public void shouldMatchVarArgs_twoArgsTwoAnyMatcher() {
+ mock.varargs(1, 2);
+
+ verify(mock).varargs(any(), any()); // any() -> VarargMatcher
+ }
+
+ @Test
+ public void shouldMatchVarArgs_twoArgsThreeAnyMatcher() {
+ mock.varargs(1, 2);
+
+ exception.expectMessage("Argument(s) are different");
+
+ verify(mock).varargs(any(), any(), any()); //any() -> VarargMatcher
+ }
+
+ @Test
+ public void shouldMatchVarArgs_oneNullArgument() {
+ mock.varargs("1", null);
+
+ verify(mock).varargs(eq("1"), (String) isNull());
+ }
+
+ @Test
+ public void shouldMatchVarArgs_onebyte() {
+ mock.varargsbyte((byte) 1);
+
+ verify(mock).varargsbyte(eq((byte) 1));
+ }
+
+ @Test
+ public void shouldMatchVarArgs_nullByteArray() {
+ mock.varargsbyte(null);
+
+ verify(mock).varargsbyte((byte[]) isNull());
+ }
+
+ @Test
+ public void shouldMatchVarArgs_emptyByteArray() {
+ mock.varargsbyte();
+
+ verify(mock).varargsbyte();
+ }
+
+ @Test
+ @Ignore
+ public void shouldMatchEmptyVarArgs_emptyArrayIsNotNull() {
+ mock.varargsbyte();
+
+ verify(mock).varargsbyte((byte[]) isNotNull());
+ }
+
+ @Test
+ public void shouldMatchVarArgs_oneArgIsNotNull() {
+ mock.varargsbyte((byte) 1);
+
+ verify(mock).varargsbyte((byte[]) isNotNull());
+ }
+
+ @Test
+ public void shouldCaptureVarArgs_noArgs() {
+ mock.varargs();
+
+ verify(mock).varargs(captor.capture());
+
+ assertThat(captor).isEmpty();
+ }
+
+ @Test
+ public void shouldCaptureVarArgs_oneNullArg_eqNull() {
+ String arg = null;
+ mock.varargs(arg);
+
+ verify(mock).varargs(captor.capture());
+
+ assertThat(captor).areExactly(1, NULL);
+ }
+
+ /**
+ * Relates to Github issue #583 "ArgumentCaptor: NPE when an null array is
+ * passed to a varargs method"
+ */
+ @Test
+ public void shouldCaptureVarArgs_nullArrayArg() {
+ String[] argArray = null;
+ mock.varargs(argArray);
+
+ verify(mock).varargs(captor.capture());
+ assertThat(captor).areExactly(1, NULL);
+ }
+
+ @Test
+ public void shouldCaptureVarArgs_twoArgsOneCapture() {
+ mock.varargs("1", "2");
+
+ verify(mock).varargs(captor.capture());
+
+ assertThat(captor).contains("1", "2");
+ }
+
+ @Test
+ public void shouldCaptureVarArgs_twoArgsTwoCaptures() {
+ mock.varargs("1", "2");
+
+ verify(mock).varargs(captor.capture(), captor.capture());
+
+ assertThat(captor).contains("1", "2");
+ }
+
+ @Test
+ public void shouldCaptureVarArgs_oneNullArgument() {
+ mock.varargs("1", null);
+
+ verify(mock).varargs(captor.capture());
+
+ assertThat(captor).contains("1", (String) null);
+ }
+
+ @Test
+ public void shouldCaptureVarArgs_oneNullArgument2() {
+ mock.varargs("1", null);
+
+ verify(mock).varargs(captor.capture(), captor.capture());
+
+ assertThat(captor).contains("1", (String) null);
+ }
+
+ @Test
+ public void shouldNotCaptureVarArgs_3args2captures() {
+ mock.varargs("1", "2", "3");
+
+ exception.expect(ArgumentsAreDifferent.class);
+
+ verify(mock).varargs(captor.capture(), captor.capture());
+
+ }
+
+ @Test
+ public void shouldCaptureVarArgs_3argsCaptorMatcherMix() {
+ mock.varargs("1", "2", "3");
+
+ verify(mock).varargs(captor.capture(), eq("2"), captor.capture());
+
+ assertThat(captor).containsExactly("1", "3");
+
+ }
+
+ @Test
+ public void shouldNotCaptureVarArgs_3argsCaptorMatcherMix() {
+ mock.varargs("1", "2", "3");
+
+ try {
+ verify(mock).varargs(captor.capture(), eq("X"), captor.capture());
+ fail("The verification must fail, cause the second arg was not 'X' as expected!");
+ } catch (ArgumentsAreDifferent expected) {
+ }
+
+ assertThat(captor).isEmpty();
+
+ }
+
+ @Test
+ public void shouldNotCaptureVarArgs_1args2captures() {
+ mock.varargs("1");
+
+ exception.expect(ArgumentsAreDifferent.class);
+
+ verify(mock).varargs(captor.capture(), captor.capture());
+
+ }
+
+ /**
+ * As of v2.0.0-beta.118 this test fails. Once the github issues:
+ * <ul>
+ * <li>'#584 ArgumentCaptor can't capture varargs-arrays
+ * <li>#565 ArgumentCaptor should be type aware' are fixed this test must
+ * succeed
+ * </ul>
+ *
+ * @throws Exception
+ */
+ @Test
+ @Ignore("Blocked by github issue: #584 & #565")
+ public void shouldCaptureVarArgsAsArray() {
+ mock.varargs("1", "2");
+
+ ArgumentCaptor<String[]> varargCaptor = ArgumentCaptor.forClass(String[].class);
+
+ verify(mock).varargs(varargCaptor.capture());
+
+ assertThat(varargCaptor).containsExactly(new String[] { "1", "2" });
+ }
+
+ @Test
+ public void shouldNotMatchRegualrAndVaraArgs() {
+ mock.varargsString(1, "a","b");
+
+ exception.expect(ArgumentsAreDifferent.class);
+
+ verify(mock).varargsString(1);
+ }
+ @Test
+ public void shouldNotMatchVaraArgs() {
+ when(mock.varargsObject(1, "a","b")).thenReturn("OK");
+
+ Assertions.assertThat(mock.varargsObject(1)).isNull();
+ }
+
+ private static <T> AbstractListAssert<?, ?, T> assertThat(ArgumentCaptor<T> captor) {
+ return Assertions.assertThat(captor.getAllValues());
+ }
+}
\ No newline at end of file
| val | train | 2016-09-29T14:46:49 | "2016-06-18T21:51:46Z" | ChristianSchwarz | train |
mockito/mockito/583_635 | mockito/mockito | mockito/mockito/583 | mockito/mockito/635 | [
"keyword_pr_to_issue"
] | 0fcad43a0a341fc4e3698c9b30faf377018b7b7e | 120d2204f8ebe68b5c3d6c3e587df40777a5a3a5 | [
"Probably related to #567\n"
] | [] | "2016-09-12T20:15:57Z" | [
"bug"
] | ArgumentCaptor: NPE when an null array is passed to a varargs method | A NullPointerException is thrown if an null array is passed to a varargs method.
```
@Test
public void shouldCaptureVarArgs_nullArrayArg() {
String[] argArray = null;
mock.varargs(argArray);
verify(mock).varargs(captor.capture()); //<- Kaboom NPE
}
```
Since an vararg is simply an array the ArgumentCaptor should reject it silently. This relates to #565.
```
java.lang.NullPointerException
at java.lang.reflect.Array.getLength(Native Method)
at org.mockito.internal.invocation.InvocationMatcher.captureVarargsPart(InvocationMatcher.java:142)
at org.mockito.internal.invocation.InvocationMatcher.captureArgumentsFrom(InvocationMatcher.java:122)
at org.mockito.internal.invocation.InvocationMarker.markVerified(InvocationMarker.java:24)
at org.mockito.internal.invocation.InvocationMarker.markVerified(InvocationMarker.java:18)
at org.mockito.internal.verification.checkers.NumberOfInvocationsChecker.check(NumberOfInvocationsChecker.java:43)
at org.mockito.internal.verification.Times.verify(Times.java:40)
at org.mockito.internal.verification.MockAwareVerificationMode.verify(MockAwareVerificationMode.java:21)
at org.mockito.internal.handler.MockHandlerImpl.handle(MockHandlerImpl.java:73)
at org.mockito.internal.handler.NullResultGuardian.handle(NullResultGuardian.java:32)
at org.mockito.internal.handler.InvocationNotifierHandler.handle(InvocationNotifierHandler.java:37)
at org.mockito.internal.creation.bytebuddy.MockMethodInterceptor.doIntercept(MockMethodInterceptor.java:36)
at org.mockito.internal.creation.bytebuddy.MockMethodInterceptor.access$0(MockMethodInterceptor.java:32)
at org.mockito.internal.creation.bytebuddy.MockMethodInterceptor$DispatcherDefaultingToRealMethod.interceptAbstract(MockMethodInterceptor.java:113)
at org.mockitousage.IMethods$MockitoMock$81506210.varargs(Unknown Source)
at org.mockitousage.matchers.VarargsTest.shouldCaptureVarArgs_nullArrayArg(VarargsTest.java:182)
```
| [
"src/main/java/org/mockito/internal/invocation/ArgumentsComparator.java",
"src/main/java/org/mockito/internal/invocation/InvocationMatcher.java"
] | [
"src/main/java/org/mockito/internal/invocation/ArgumentMatcherAction.java",
"src/main/java/org/mockito/internal/invocation/InvocationMatcher.java",
"src/main/java/org/mockito/internal/invocation/MatcherApplicationStrategy.java",
"src/main/java/org/mockito/internal/invocation/TypeSafeMatching.java"
] | [
"src/test/java/org/mockito/internal/invocation/MatcherApplicationStrategyTest.java",
"src/test/java/org/mockito/internal/invocation/TypeSafeMatchingTest.java",
"src/test/java/org/mockito/internal/util/reflection/FieldInitializerTest.java",
"src/test/java/org/mockitousage/matchers/VarargsTest.java"
] | diff --git a/src/main/java/org/mockito/internal/invocation/ArgumentMatcherAction.java b/src/main/java/org/mockito/internal/invocation/ArgumentMatcherAction.java
new file mode 100644
index 0000000000..29156d0b4c
--- /dev/null
+++ b/src/main/java/org/mockito/internal/invocation/ArgumentMatcherAction.java
@@ -0,0 +1,28 @@
+package org.mockito.internal.invocation;
+
+import org.mockito.ArgumentMatcher;
+
+public interface ArgumentMatcherAction {
+ /**
+ * Implementations must apply the given matcher to the argument and return
+ * <code>true</code> if the operation was successful or <code>false</code>
+ * if not. In this case no more matchers and arguments will be passed by
+ * {@link MatcherApplicationStrategy#forEachMatcherAndArgument(ArgumentMatcherAction)} to this method.
+ * .
+ *
+ * @param matcher
+ * to process the argument, never <code>null</code>
+ * @param argument
+ * to be processed by the matcher, can be <code>null</code>
+ * @return
+ * <ul>
+ * <li><code>true</code> if the <b>matcher</b> was successfully
+ * applied to the <b>argument</b> and the next pair of matcher and
+ * argument should be passed
+ * <li><code>false</code> otherwise
+ * </ul>
+ *
+ *
+ */
+ boolean apply(ArgumentMatcher<?> matcher, Object argument);
+}
diff --git a/src/main/java/org/mockito/internal/invocation/ArgumentsComparator.java b/src/main/java/org/mockito/internal/invocation/ArgumentsComparator.java
deleted file mode 100644
index 7b12fb2aff..0000000000
--- a/src/main/java/org/mockito/internal/invocation/ArgumentsComparator.java
+++ /dev/null
@@ -1,117 +0,0 @@
-/*
- * Copyright (c) 2007 Mockito contributors
- * This program is made available under the terms of the MIT License.
- */
-package org.mockito.internal.invocation;
-
-import java.lang.reflect.Method;
-import java.util.List;
-import org.mockito.ArgumentMatcher;
-import org.mockito.internal.matchers.VarargMatcher;
-import org.mockito.invocation.Invocation;
-
-@SuppressWarnings("unchecked")
-public class ArgumentsComparator {
-
- private ArgumentsComparator() {}
-
- public static boolean argumentsMatch(InvocationMatcher invocationMatcher, Invocation actual) {
- Object[] actualArgs = actual.getArguments();
- return argumentsMatch(invocationMatcher, actualArgs) || varArgsMatch(invocationMatcher, actual);
- }
-
- public static boolean argumentsMatch(InvocationMatcher invocationMatcher, Object[] actualArgs) {
- if (actualArgs.length != invocationMatcher.getMatchers().size()) {
- return false;
- }
- for (int i = 0; i < actualArgs.length; i++) {
- ArgumentMatcher<Object> argumentMatcher = invocationMatcher.getMatchers().get(i);
- Object argument = actualArgs[i];
-
- if (!matches(argumentMatcher, argument)) {
- return false;
- }
- }
- return true;
- }
-
- // ok, this method is a little bit messy but the vararg business unfortunately is messy...
- private static boolean varArgsMatch(InvocationMatcher invocationMatcher, Invocation actual) {
- if (!actual.getMethod().isVarArgs()) {
- // if the method is not vararg forget about it
- return false;
- }
-
- // we must use raw arguments, not arguments...
- Object[] rawArgs = actual.getRawArguments();
- List<ArgumentMatcher> matchers = invocationMatcher.getMatchers();
-
- if (rawArgs.length != matchers.size()) {
- return false;
- }
-
- for (int i = 0; i < rawArgs.length; i++) {
- ArgumentMatcher m = matchers.get(i);
- // it's a vararg because it's the last array in the arg list
- if (rawArgs[i] != null && rawArgs[i].getClass().isArray() && i == rawArgs.length - 1) {
- // this is very important to only allow VarargMatchers here. If
- // you're not sure why remove it and run all tests.
- if (!(m instanceof VarargMatcher) || !m.matches(rawArgs[i])) {
- return false;
- }
- // it's not a vararg (i.e. some ordinary argument before
- // varargs), just do the ordinary check
- } else if (!m.matches(rawArgs[i])) {
- return false;
- }
- }
-
- return true;
- }
-
- private static boolean matches(ArgumentMatcher<Object> argumentMatcher, Object argument) {
- return isCompatible(argumentMatcher, argument) && argumentMatcher.matches(argument);
- }
-
- /**
- * Returns <code>true</code> if the given <b>argument</b> can be passed to
- * the given <code>argumentMatcher</code> without causing a
- * {@link ClassCastException}.
- */
- private static boolean isCompatible(ArgumentMatcher<?> argumentMatcher, Object argument) {
- if (argument == null)
- return true;
-
- Class<?> expectedArgumentType = getArgumentType(argumentMatcher);
-
- return expectedArgumentType.isInstance(argument);
- }
-
- /**
- * Returns the type of {@link ArgumentMatcher#matches(Object)} of the given
- * {@link ArgumentMatcher} implementation.
- */
- private static Class<?> getArgumentType(ArgumentMatcher<?> argumentMatcher) {
- Method[] methods = argumentMatcher.getClass().getMethods();
- for (Method method : methods) {
- if (isMatchesMethod(method)) {
- return method.getParameterTypes()[0];
- }
- }
- throw new NoSuchMethodError("Method 'matches(T)' not found in ArgumentMatcher: " + argumentMatcher + " !\r\n Please file a bug with this stack trace at: https://github.com/mockito/mockito/issues/new ");
- }
-
- /**
- * Returns <code>true</code> if the given method is
- * {@link ArgumentMatcher#matches(Object)}
- */
- private static boolean isMatchesMethod(Method method) {
- if (method.getParameterTypes().length != 1) {
- return false;
- }
- if (method.isBridge()) {
- return false;
- }
- return method.getName().equals("matches");
- }
-}
diff --git a/src/main/java/org/mockito/internal/invocation/InvocationMatcher.java b/src/main/java/org/mockito/internal/invocation/InvocationMatcher.java
index 66ea8f5fbf..d955b70013 100644
--- a/src/main/java/org/mockito/internal/invocation/InvocationMatcher.java
+++ b/src/main/java/org/mockito/internal/invocation/InvocationMatcher.java
@@ -5,6 +5,15 @@
package org.mockito.internal.invocation;
+import static org.mockito.internal.invocation.ArgumentsProcessor.argumentsToMatchers;
+import static org.mockito.internal.invocation.MatcherApplicationStrategy.getMatcherApplicationStrategyFor;
+import static org.mockito.internal.invocation.TypeSafeMatching.matchesTypeSafe;
+
+import java.io.Serializable;
+import java.lang.reflect.Method;
+import java.util.Collections;
+import java.util.LinkedList;
+import java.util.List;
import org.mockito.ArgumentMatcher;
import org.mockito.internal.matchers.CapturesArguments;
import org.mockito.internal.reporting.PrintSettings;
@@ -12,36 +21,36 @@
import org.mockito.invocation.Invocation;
import org.mockito.invocation.Location;
-import static org.mockito.internal.invocation.ArgumentsComparator.argumentsMatch;
-
-import java.io.Serializable;
-import java.lang.reflect.Array;
-import java.lang.reflect.Method;
-import java.util.*;
-
-@SuppressWarnings("unchecked")
/**
- * In addition to all content of the invocation, the invocation matcher contains the argument matchers.
- * Invocation matcher is used during verification and stubbing.
- * In those cases, the user can provide argument matchers instead of 'raw' arguments.
- * Raw arguments are converted to 'equals' matchers anyway.
+ * In addition to all content of the invocation, the invocation matcher contains the argument matchers. Invocation matcher is used during verification and stubbing. In those cases, the user can provide argument matchers instead of 'raw' arguments. Raw arguments are converted to 'equals' matchers anyway.
*/
+@SuppressWarnings("serial")
public class InvocationMatcher implements DescribedInvocation, CapturesArgumentsFromInvocation, Serializable {
private final Invocation invocation;
- private final List<ArgumentMatcher> matchers;
+ private final List<ArgumentMatcher<?>> matchers;
+ @SuppressWarnings({ "rawtypes", "unchecked" })
public InvocationMatcher(Invocation invocation, List<ArgumentMatcher> matchers) {
this.invocation = invocation;
if (matchers.isEmpty()) {
- this.matchers = ArgumentsProcessor.argumentsToMatchers(invocation.getArguments());
+ this.matchers = (List) argumentsToMatchers(invocation.getArguments());
} else {
- this.matchers = matchers;
+ this.matchers = (List) matchers;
}
}
+ @SuppressWarnings("rawtypes")
public InvocationMatcher(Invocation invocation) {
- this(invocation, Collections.<ArgumentMatcher>emptyList());
+ this(invocation, Collections.<ArgumentMatcher> emptyList());
+ }
+
+ public static List<InvocationMatcher> createFrom(List<Invocation> invocations) {
+ LinkedList<InvocationMatcher> out = new LinkedList<InvocationMatcher>();
+ for (Invocation i : invocations) {
+ out.add(new InvocationMatcher(i));
+ }
+ return out;
}
public Method getMethod() {
@@ -49,54 +58,50 @@ public Method getMethod() {
}
public Invocation getInvocation() {
- return this.invocation;
+ return invocation;
}
+ @SuppressWarnings({ "unchecked", "rawtypes" })
public List<ArgumentMatcher> getMatchers() {
- return this.matchers;
+ return (List) matchers;
}
+ @Override
+ @SuppressWarnings({ "unchecked", "rawtypes" })
public String toString() {
- return new PrintSettings().print(matchers, invocation);
+ return new PrintSettings().print((List) matchers, invocation);
}
public boolean matches(Invocation actual) {
- return invocation.getMock().equals(actual.getMock())
- && hasSameMethod(actual)
- && argumentsMatch(this, actual);
- }
-
- private boolean safelyArgumentsMatch(Object[] actualArgs) {
- try {
- return argumentsMatch(this, actualArgs);
- } catch (Throwable t) {
- return false;
- }
+ return invocation.getMock().equals(actual.getMock()) && hasSameMethod(actual) && argumentsMatch(actual);
}
/**
- * similar means the same method name, same mock, unverified
- * and: if arguments are the same cannot be overloaded
+ * similar means the same method name, same mock, unverified and: if arguments are the same cannot be overloaded
*/
public boolean hasSimilarMethod(Invocation candidate) {
String wantedMethodName = getMethod().getName();
- String currentMethodName = candidate.getMethod().getName();
-
- final boolean methodNameEquals = wantedMethodName.equals(currentMethodName);
- final boolean isUnverified = !candidate.isVerified();
- final boolean mockIsTheSame = getInvocation().getMock() == candidate.getMock();
- final boolean methodEquals = hasSameMethod(candidate);
+ String candidateMethodName = candidate.getMethod().getName();
- if (!methodNameEquals || !isUnverified || !mockIsTheSame) {
+ if (!wantedMethodName.equals(candidateMethodName)) {
return false;
}
+ if (candidate.isVerified()) {
+ return false;
+ }
+ if (getInvocation().getMock() != candidate.getMock()) {
+ return false;
+ }
+ if (hasSameMethod(candidate)) {
+ return true;
+ }
- final boolean overloadedButSameArgs = !methodEquals && safelyArgumentsMatch(candidate.getArguments());
-
- return !overloadedButSameArgs;
+ return !argumentsMatch(candidate);
}
public boolean hasSameMethod(Invocation candidate) {
+ // not using method.equals() for 1 good reason:
+ // sometimes java generates forwarding methods when generics are in play see JavaGenericsForwardingMethodsTest
Method m1 = invocation.getMethod();
Method m2 = candidate.getMethod();
@@ -115,59 +120,34 @@ public boolean hasSameMethod(Invocation candidate) {
return false;
}
+ @Override
public Location getLocation() {
return invocation.getLocation();
}
+ @Override
public void captureArgumentsFrom(Invocation invocation) {
- captureRegularArguments(invocation);
- captureVarargsPart(invocation);
+ MatcherApplicationStrategy strategy = getMatcherApplicationStrategyFor(invocation, matchers);
+ strategy.forEachMatcherAndArgument(captureArgument());
}
- private void captureRegularArguments(Invocation invocation) {
- for (int position = 0; position < regularArgumentsSize(invocation); position++) {
- ArgumentMatcher m = matchers.get(position);
- if (m instanceof CapturesArguments) {
- ((CapturesArguments) m).captureFrom(invocation.getArgument(position));
- }
- }
- }
-
- private void captureVarargsPart(Invocation invocation) {
- if (!invocation.getMethod().isVarArgs()) {
- return;
- }
- int indexOfVararg = invocation.getRawArguments().length - 1;
- for (ArgumentMatcher m : uniqueMatcherSet(indexOfVararg)) {
- if (m instanceof CapturesArguments) {
- Object rawArgument = invocation.getRawArguments()[indexOfVararg];
- for (int i = 0; i < Array.getLength(rawArgument); i++) {
- ((CapturesArguments) m).captureFrom(Array.get(rawArgument, i));
+ private ArgumentMatcherAction captureArgument() {
+ return new ArgumentMatcherAction() {
+
+ @Override
+ public boolean apply(ArgumentMatcher<?> matcher, Object argument) {
+ if (matcher instanceof CapturesArguments) {
+ ((CapturesArguments) matcher).captureFrom(argument);
}
+
+ return true;
}
- }
- }
-
- private int regularArgumentsSize(Invocation invocation) {
- return invocation.getMethod().isVarArgs() ?
- invocation.getRawArguments().length - 1 // ignores vararg holder array
- : matchers.size();
- }
-
- private Set<ArgumentMatcher> uniqueMatcherSet(int indexOfVararg) {
- HashSet<ArgumentMatcher> set = new HashSet<ArgumentMatcher>();
- for (int position = indexOfVararg; position < matchers.size(); position++) {
- ArgumentMatcher matcher = matchers.get(position);
- set.add(matcher);
- }
- return set;
+ };
}
-
- public static List<InvocationMatcher> createFrom(List<Invocation> invocations) {
- LinkedList<InvocationMatcher> out = new LinkedList<InvocationMatcher>();
- for (Invocation i : invocations) {
- out.add(new InvocationMatcher(i));
- }
- return out;
+
+ @SuppressWarnings({ "rawtypes", "unchecked" })
+ private boolean argumentsMatch(Invocation actual) {
+ List matchers = getMatchers();
+ return getMatcherApplicationStrategyFor(actual, matchers).forEachMatcherAndArgument( matchesTypeSafe());
}
-}
+}
\ No newline at end of file
diff --git a/src/main/java/org/mockito/internal/invocation/MatcherApplicationStrategy.java b/src/main/java/org/mockito/internal/invocation/MatcherApplicationStrategy.java
new file mode 100644
index 0000000000..40c6519c91
--- /dev/null
+++ b/src/main/java/org/mockito/internal/invocation/MatcherApplicationStrategy.java
@@ -0,0 +1,128 @@
+package org.mockito.internal.invocation;
+
+import static org.mockito.internal.invocation.MatcherApplicationStrategy.MatcherApplicationType.ERROR_UNSUPPORTED_NUMBER_OF_MATCHERS;
+import static org.mockito.internal.invocation.MatcherApplicationStrategy.MatcherApplicationType.MATCH_EACH_VARARGS_WITH_LAST_MATCHER;
+import static org.mockito.internal.invocation.MatcherApplicationStrategy.MatcherApplicationType.ONE_MATCHER_PER_ARGUMENT;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.mockito.ArgumentMatcher;
+import org.mockito.internal.matchers.CapturingMatcher;
+import org.mockito.internal.matchers.VarargMatcher;
+import org.mockito.invocation.Invocation;
+
+public class MatcherApplicationStrategy {
+
+ private final Invocation invocation;
+ private final List<ArgumentMatcher<?>> matchers;
+ private final MatcherApplicationType matchingType;
+
+
+
+ private MatcherApplicationStrategy(Invocation invocation, List<ArgumentMatcher<?>> matchers, MatcherApplicationType matchingType) {
+ this.invocation = invocation;
+ if (matchingType == MATCH_EACH_VARARGS_WITH_LAST_MATCHER) {
+ int times = varargLength(invocation);
+ this.matchers = appendLastMatcherNTimes(matchers, times);
+ } else {
+ this.matchers = matchers;
+ }
+
+ this.matchingType = matchingType;
+ }
+
+ /**
+ * Returns the {@link MatcherApplicationStrategy} that must be used to capture the
+ * arguments of the given <b>invocation</b> using the given <b>matchers</b>.
+ *
+ * @param invocation
+ * that contain the arguments to capture
+ * @param matchers
+ * that will be used to capture the arguments of the invocation,
+ * the passed {@link List} is not required to contain a
+ * {@link CapturingMatcher}
+ * @return never <code>null</code>
+ */
+ public static MatcherApplicationStrategy getMatcherApplicationStrategyFor(Invocation invocation, List<ArgumentMatcher<?>> matchers) {
+
+ MatcherApplicationType type = getMatcherApplicationType(invocation, matchers);
+ return new MatcherApplicationStrategy(invocation, matchers, type);
+ }
+
+ /**
+ * Applies the given {@link ArgumentMatcherAction} to all arguments and
+ * corresponding matchers
+ *
+ * @param action
+ * must not be <code>null</code>
+ * @return
+ * <ul>
+ * <li><code>true</code> if the given <b>action</b> returned
+ * <code>true</code> for all arguments and matchers passed to it.
+ * <li><code>false</code> if the given <b>action</b> returned
+ * <code>false</code> for one of the passed arguments and matchers
+ * <li><code>false</code> if the given matchers don't fit to the given invocation
+ * because too many or to few matchers are available.
+ * </ul>
+ */
+ public boolean forEachMatcherAndArgument(ArgumentMatcherAction action) {
+ if (matchingType == ERROR_UNSUPPORTED_NUMBER_OF_MATCHERS)
+ return false;
+
+ Object[] arguments = invocation.getArguments();
+ for (int i = 0; i < arguments.length; i++) {
+ ArgumentMatcher<?> matcher = matchers.get(i);
+ Object argument = arguments[i];
+
+ if (!action.apply(matcher, argument)) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ private static MatcherApplicationType getMatcherApplicationType(Invocation invocation, List<ArgumentMatcher<?>> matchers) {
+ final int rawArguments = invocation.getRawArguments().length;
+ final int expandedArguments = invocation.getArguments().length;
+ final int matcherCount = matchers.size();
+
+ if (expandedArguments == matcherCount) {
+ return ONE_MATCHER_PER_ARGUMENT;
+ }
+
+ if (rawArguments == matcherCount && isLastMatcherVargargMatcher(matchers)) {
+ return MATCH_EACH_VARARGS_WITH_LAST_MATCHER;
+ }
+
+ return ERROR_UNSUPPORTED_NUMBER_OF_MATCHERS;
+ }
+
+ private static boolean isLastMatcherVargargMatcher(final List<ArgumentMatcher<?>> matchers) {
+ return lastMatcher(matchers) instanceof VarargMatcher;
+ }
+
+ private static List<ArgumentMatcher<?>> appendLastMatcherNTimes(List<ArgumentMatcher<?>> matchers, int timesToAppendLastMatcher) {
+ ArgumentMatcher<?> lastMatcher = lastMatcher(matchers);
+
+ List<ArgumentMatcher<?>> expandedMatchers = new ArrayList<ArgumentMatcher<?>>(matchers);
+ for (int i = 0; i < timesToAppendLastMatcher; i++) {
+ expandedMatchers.add(lastMatcher);
+ }
+ return expandedMatchers;
+ }
+
+ private static int varargLength(Invocation invocation) {
+ int rawArgumentCount = invocation.getRawArguments().length;
+ int expandedArgumentCount = invocation.getArguments().length;
+ return expandedArgumentCount - rawArgumentCount;
+ }
+
+ private static ArgumentMatcher<?> lastMatcher(List<ArgumentMatcher<?>> matchers) {
+ return matchers.get(matchers.size() - 1);
+ }
+
+ enum MatcherApplicationType {
+ ONE_MATCHER_PER_ARGUMENT, MATCH_EACH_VARARGS_WITH_LAST_MATCHER, ERROR_UNSUPPORTED_NUMBER_OF_MATCHERS;
+ }
+}
\ No newline at end of file
diff --git a/src/main/java/org/mockito/internal/invocation/TypeSafeMatching.java b/src/main/java/org/mockito/internal/invocation/TypeSafeMatching.java
new file mode 100644
index 0000000000..181e47fea9
--- /dev/null
+++ b/src/main/java/org/mockito/internal/invocation/TypeSafeMatching.java
@@ -0,0 +1,70 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.invocation;
+
+import java.lang.reflect.Method;
+
+import org.mockito.ArgumentMatcher;
+
+@SuppressWarnings({"unchecked","rawtypes"})
+public class TypeSafeMatching implements ArgumentMatcherAction {
+
+ private final static ArgumentMatcherAction TYPE_SAFE_MATCHING_ACTION = new TypeSafeMatching();
+
+ private TypeSafeMatching() {}
+
+
+ public static ArgumentMatcherAction matchesTypeSafe(){
+ return TYPE_SAFE_MATCHING_ACTION;
+ }
+ @Override
+ public boolean apply(ArgumentMatcher matcher, Object argument) {
+ return isCompatible(matcher, argument) && matcher.matches(argument);
+ }
+
+
+ /**
+ * Returns <code>true</code> if the given <b>argument</b> can be passed to
+ * the given <code>argumentMatcher</code> without causing a
+ * {@link ClassCastException}.
+ */
+ private static boolean isCompatible(ArgumentMatcher<?> argumentMatcher, Object argument) {
+ if (argument == null)
+ return true;
+
+ Class<?> expectedArgumentType = getArgumentType(argumentMatcher);
+
+ return expectedArgumentType.isInstance(argument);
+ }
+
+ /**
+ * Returns the type of {@link ArgumentMatcher#matches(Object)} of the given
+ * {@link ArgumentMatcher} implementation.
+ */
+ private static Class<?> getArgumentType(ArgumentMatcher<?> argumentMatcher) {
+ Method[] methods = argumentMatcher.getClass().getMethods();
+
+ for (Method method : methods) {
+ if (isMatchesMethod(method)) {
+ return method.getParameterTypes()[0];
+ }
+ }
+ throw new NoSuchMethodError("Method 'matches(T)' not found in ArgumentMatcher: " + argumentMatcher + " !\r\n Please file a bug with this stack trace at: https://github.com/mockito/mockito/issues/new ");
+ }
+
+ /**
+ * Returns <code>true</code> if the given method is
+ * {@link ArgumentMatcher#matches(Object)}
+ */
+ private static boolean isMatchesMethod(Method method) {
+ if (method.getParameterTypes().length != 1) {
+ return false;
+ }
+ if (method.isBridge()) {
+ return false;
+ }
+ return method.getName().equals("matches");
+ }
+}
\ No newline at end of file
| diff --git a/src/test/java/org/mockito/internal/invocation/ArgumentsComparatorTest.java b/src/test/java/org/mockito/internal/invocation/ArgumentsComparatorTest.java
deleted file mode 100644
index 9aed7c77e7..0000000000
--- a/src/test/java/org/mockito/internal/invocation/ArgumentsComparatorTest.java
+++ /dev/null
@@ -1,205 +0,0 @@
-/*
- * Copyright (c) 2007 Mockito contributors
- * This program is made available under the terms of the MIT License.
- */
-package org.mockito.internal.invocation;
-
-import static java.util.Arrays.asList;
-import static junit.framework.TestCase.assertFalse;
-import static junit.framework.TestCase.assertTrue;
-import static org.mockito.internal.invocation.ArgumentsComparator.argumentsMatch;
-import static org.mockito.internal.matchers.Any.ANY;
-
-import java.util.List;
-import org.junit.Test;
-import org.mockito.Mock;
-import org.mockito.internal.matchers.Any;
-import org.mockito.internal.matchers.Equals;
-import org.mockito.internal.matchers.InstanceOf;
-import org.mockito.invocation.Invocation;
-import org.mockitousage.IMethods;
-import org.mockitoutil.TestBase;
-
-@SuppressWarnings("unchecked")
-public class ArgumentsComparatorTest extends TestBase {
-
- @Mock IMethods mock;
-
- @Test
- public void shouldKnowWhenArgumentsMatch() {
- //given
- Invocation invocation = new InvocationBuilder().args("1", 100).toInvocation();
- InvocationMatcher invocationMatcher = new InvocationBuilder().args("1", 100).toInvocationMatcher();
-
- //when
- boolean match = argumentsMatch(invocationMatcher, invocation);
-
- //then
- assertTrue(match);
- }
-
- @Test
- public void shouldKnowWhenArgsDifferent() {
- //given
- Invocation invocation = new InvocationBuilder().args("1", 100).toInvocation();
- InvocationMatcher invocationMatcher = new InvocationBuilder().args("100", 100).toInvocationMatcher();
-
- //when
- boolean match = argumentsMatch(invocationMatcher, invocation);
-
- //then
- assertFalse(match);
- }
-
- @Test
- public void shouldKnowWhenActualArgsSizeIsDifferent() {
- //given
- Invocation invocation = new InvocationBuilder().args("100", 100).toInvocation();
- InvocationMatcher invocationMatcher = new InvocationBuilder().args("100").toInvocationMatcher();
-
- //when
- boolean match = argumentsMatch(invocationMatcher, invocation);
-
- //then
- assertFalse(match);
- }
-
- @Test
- public void shouldKnowWhenMatchersSizeIsDifferent() {
- //given
- Invocation invocation = new InvocationBuilder().args("100").toInvocation();
- InvocationMatcher invocationMatcher = new InvocationBuilder().args("100", 100).toInvocationMatcher();
-
- //when
- boolean match = argumentsMatch(invocationMatcher, invocation);
-
- //then
- assertFalse(match);
- }
-
- @Test
- public void shouldKnowWhenVarargsMatch() {
- //given
- mock.varargs("1", "2", "3");
- Invocation invocation = getLastInvocation();
- InvocationMatcher invocationMatcher = new InvocationMatcher(invocation, (List) asList(new Equals("1"), Any.ANY, new InstanceOf(String.class)));
-
- //when
- boolean match = argumentsMatch(invocationMatcher, invocation);
-
- //then
- assertTrue(match);
- }
-
- @Test
- public void shouldKnowWhenVarargsDifferent() {
- //given
- mock.varargs("1", "2");
- Invocation invocation = getLastInvocation();
- InvocationMatcher invocationMatcher = new InvocationMatcher(invocation, (List) asList(new Equals("100"), Any.ANY));
-
- //when
- boolean match = argumentsMatch(invocationMatcher, invocation);
-
- //then
- assertFalse(match);
- }
-
- @Test
- public void shouldAllowAnyVarargMatchEntireVararg() {
- //given
- mock.varargs("1", "2");
- Invocation invocation = getLastInvocation();
- InvocationMatcher invocationMatcher = new InvocationMatcher(invocation, (List) asList(ANY));
-
- //when
- boolean match = argumentsMatch(invocationMatcher, invocation);
-
- //then
- assertTrue(match);
- }
-
- @Test
- public void shouldNotAllowAnyObjectWithMixedVarargs() {
- //given
- mock.mixedVarargs(1, "1", "2");
- Invocation invocation = getLastInvocation();
- InvocationMatcher invocationMatcher = new InvocationMatcher(invocation, (List) asList(new Equals(1)));
-
- //when
- boolean match = argumentsMatch(invocationMatcher, invocation);
-
- //then
- assertFalse(match);
- }
-
- @Test
- public void shouldAllowAnyObjectWithMixedVarargs() {
- //given
- mock.mixedVarargs(1, "1", "2");
- Invocation invocation = getLastInvocation();
- InvocationMatcher invocationMatcher = new InvocationMatcher(invocation, (List) asList(new Equals(1), ANY));
-
- //when
- boolean match = argumentsMatch(invocationMatcher, invocation);
-
- //then
- assertTrue(match);
- }
-
- @Test
- public void shouldNotMatchWhenSomeOtherArgumentDoesNotMatch() {
- //given
- mock.mixedVarargs(1, "1", "2");
- Invocation invocation = getLastInvocation();
- InvocationMatcher invocationMatcher = new InvocationMatcher(invocation, (List) asList(new Equals(100), ANY));
-
- //when
- boolean match = argumentsMatch(invocationMatcher, invocation);
-
- //then
- assertFalse(match);
- }
-
- @Test
- public void shouldAnyObjectVarargDealWithDifferentSizeOfArgs() {
- //given
- mock.mixedVarargs(1, "1", "2");
- Invocation invocation = getLastInvocation();
- InvocationMatcher invocationMatcher = new InvocationMatcher(invocation, (List) asList(new Equals(1)));
-
- //when
- boolean match = argumentsMatch(invocationMatcher, invocation);
-
- //then
- assertFalse(match);
- }
-
- @Test
- public void shouldMatchAnyVarargEvenIfOneOfTheArgsIsNull() {
- //given
- mock.mixedVarargs(null, null, "2");
- Invocation invocation = getLastInvocation();
- InvocationMatcher invocationMatcher = new InvocationMatcher(invocation, (List) asList(new Equals(null), ANY));
-
- //when
- boolean match = argumentsMatch(invocationMatcher, invocation);
-
- //then
- assertTrue(match);
- }
-
- @Test
- public void shouldMatchAnyVarargEvenIfMatcherIsDecorated() {
- //given
- mock.varargs("1", "2");
- Invocation invocation = getLastInvocation();
- InvocationMatcher invocationMatcher = new InvocationMatcher(invocation, (List)asList(ANY));
-
- //when
- boolean match = argumentsMatch(invocationMatcher, invocation);
-
- //then
- assertTrue(match);
- }
-}
\ No newline at end of file
diff --git a/src/test/java/org/mockito/internal/invocation/MatcherApplicationStrategyTest.java b/src/test/java/org/mockito/internal/invocation/MatcherApplicationStrategyTest.java
new file mode 100644
index 0000000000..6a0c6c696e
--- /dev/null
+++ b/src/test/java/org/mockito/internal/invocation/MatcherApplicationStrategyTest.java
@@ -0,0 +1,231 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.invocation;
+
+import static java.util.Arrays.asList;
+import static junit.framework.TestCase.assertFalse;
+import static junit.framework.TestCase.assertTrue;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.internal.invocation.MatcherApplicationStrategy.getMatcherApplicationStrategyFor;
+import static org.mockito.internal.matchers.Any.ANY;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.ArgumentMatcher;
+import org.mockito.Mock;
+import org.mockito.internal.matchers.Any;
+import org.mockito.internal.matchers.Equals;
+import org.mockito.internal.matchers.InstanceOf;
+import org.mockito.invocation.Invocation;
+import org.mockitousage.IMethods;
+import org.mockitoutil.TestBase;
+
+@SuppressWarnings("unchecked")
+public class MatcherApplicationStrategyTest extends TestBase {
+
+ @Mock
+ IMethods mock;
+ private Invocation invocation;
+ private List matchers;
+
+ private RecordingAction recordAction;
+
+ @Before
+ public void before() {
+ recordAction = new RecordingAction();
+ }
+
+ @Test
+ public void shouldKnowWhenActualArgsSizeIsDifferent1() {
+ // given
+ invocation = varargs("1");
+ matchers = asList(new Equals("1"));
+
+ // when
+ boolean match = getMatcherApplicationStrategyFor(invocation, matchers).forEachMatcherAndArgument(RETURN_ALWAYS_FALSE);
+
+ // then
+ assertFalse(match);
+ }
+
+ @Test
+ public void shouldKnowWhenActualArgsSizeIsDifferent2() {
+ // given
+ invocation = varargs("1");
+ matchers = asList(new Equals("1"));
+
+ // when
+ boolean match = getMatcherApplicationStrategyFor(invocation, matchers).forEachMatcherAndArgument(RETURN_ALWAYS_TRUE);
+
+ // then
+ assertTrue(match);
+ }
+
+ @Test
+ public void shouldKnowWhenActualArgsSizeIsDifferent() {
+ // given
+ invocation = varargs("1", "2");
+ matchers = asList(new Equals("1"));
+
+ // when
+ boolean match = getMatcherApplicationStrategyFor(invocation, matchers).forEachMatcherAndArgument(RETURN_ALWAYS_TRUE);
+
+ // then
+ assertFalse(match);
+ }
+
+ @Test
+ public void shouldKnowWhenMatchersSizeIsDifferent() {
+ // given
+ invocation = varargs("1");
+ matchers = asList(new Equals("1"), new Equals("2"));
+
+ // when
+ boolean match = getMatcherApplicationStrategyFor(invocation, matchers).forEachMatcherAndArgument(RETURN_ALWAYS_TRUE);
+
+ // then
+ assertFalse(match);
+ }
+
+ @Test
+ public void shouldKnowWhenVarargsMatch() {
+ // given
+ invocation = varargs("1", "2", "3");
+ matchers = asList(new Equals("1"), Any.ANY, new InstanceOf(String.class));
+
+ // when
+ boolean match = getMatcherApplicationStrategyFor(invocation, matchers).forEachMatcherAndArgument(recordAction);
+
+ // then
+ assertTrue(match);
+ }
+
+ @Test
+ public void shouldAllowAnyVarargMatchEntireVararg() {
+ // given
+ invocation = varargs("1", "2");
+ matchers = asList(ANY);
+
+ // when
+ boolean match = getMatcherApplicationStrategyFor(invocation, matchers).forEachMatcherAndArgument(recordAction);
+
+ // then
+ assertTrue(match);
+ }
+
+ @Test
+ public void shouldNotAllowAnyObjectWithMixedVarargs() {
+ // given
+ invocation = mixedVarargs(1, "1", "2");
+ matchers = asList(new Equals(1));
+
+ // when
+ boolean match = getMatcherApplicationStrategyFor(invocation, matchers).forEachMatcherAndArgument(recordAction);
+
+ // then
+ assertFalse(match);
+ }
+
+ @Test
+ public void shouldAllowAnyObjectWithMixedVarargs() {
+ // given
+ invocation = mixedVarargs(1, "1", "2");
+ matchers = asList(new Equals(1), ANY);
+
+ // when
+ boolean match = getMatcherApplicationStrategyFor(invocation, matchers).forEachMatcherAndArgument(recordAction);
+
+ // then
+ assertTrue(match);
+ }
+
+ @Test
+ public void shouldAnyObjectVarargDealWithDifferentSizeOfArgs() {
+ // given
+ invocation = mixedVarargs(1, "1", "2");
+ matchers = asList(new Equals(1));
+
+ // when
+ boolean match = getMatcherApplicationStrategyFor(invocation, matchers).forEachMatcherAndArgument(recordAction);
+
+ // then
+ assertFalse(match);
+
+ recordAction.assertIsEmpty();
+ }
+
+ @Test
+ public void shouldMatchAnyVarargEvenIfOneOfTheArgsIsNull() {
+ // given
+ invocation = mixedVarargs(null, null, "2");
+ matchers = asList(new Equals(null), ANY);
+
+ // when
+ getMatcherApplicationStrategyFor(invocation, matchers).forEachMatcherAndArgument(recordAction);
+
+ // then
+ recordAction.assertContainsExactly(new Equals(null), ANY, ANY);
+
+ }
+
+ @Test
+ public void shouldMatchAnyVarargEvenIfMatcherIsDecorated() {
+ // given
+ invocation = varargs("1", "2");
+ matchers = asList(ANY);
+
+ // when
+ getMatcherApplicationStrategyFor(invocation, matchers).forEachMatcherAndArgument(recordAction);
+
+ // then
+ recordAction.assertContainsExactly(ANY, ANY);
+ }
+
+ private Invocation mixedVarargs(Object a, String... s) {
+ mock.mixedVarargs(a, s);
+ return getLastInvocation();
+ }
+
+ private Invocation varargs(String... s) {
+ mock.varargs(s);
+ return getLastInvocation();
+ }
+
+ private class RecordingAction implements ArgumentMatcherAction {
+ private List<ArgumentMatcher<?>> matchers = new ArrayList<ArgumentMatcher<?>>();
+
+ @Override
+ public boolean apply(ArgumentMatcher<?> matcher, Object argument) {
+ matchers.add(matcher);
+ return true;
+ }
+
+ public void assertIsEmpty() {
+ assertThat(matchers).isEmpty();
+ }
+
+ public void assertContainsExactly(ArgumentMatcher<?>... matchers) {
+ assertThat(this.matchers).containsExactly(matchers);
+ }
+ }
+
+ private static final ArgumentMatcherAction RETURN_ALWAYS_TRUE = new ArgumentMatcherAction() {
+ @Override
+ public boolean apply(ArgumentMatcher<?> matcher, Object argument) {
+ return true;
+ }
+ };
+
+ private static final ArgumentMatcherAction RETURN_ALWAYS_FALSE = new ArgumentMatcherAction() {
+ @Override
+ public boolean apply(ArgumentMatcher<?> matcher, Object argument) {
+ return false;
+ }
+ };
+
+}
\ No newline at end of file
diff --git a/src/test/java/org/mockito/internal/invocation/TypeSafeMatchingTest.java b/src/test/java/org/mockito/internal/invocation/TypeSafeMatchingTest.java
new file mode 100644
index 0000000000..39deb6796f
--- /dev/null
+++ b/src/test/java/org/mockito/internal/invocation/TypeSafeMatchingTest.java
@@ -0,0 +1,163 @@
+package org.mockito.internal.invocation;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.internal.invocation.TypeSafeMatching.matchesTypeSafe;
+
+import java.util.Date;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import org.junit.Rule;
+import org.junit.Test;
+import org.mockito.ArgumentMatcher;
+import org.mockito.Mock;
+import org.mockito.internal.matchers.LessOrEqual;
+import org.mockito.internal.matchers.Null;
+import org.mockito.internal.matchers.StartsWith;
+import org.mockito.junit.MockitoJUnit;
+import org.mockito.junit.MockitoRule;
+import org.mockitousage.IMethods;
+
+public class TypeSafeMatchingTest {
+
+ private static final Object NOT_A_COMPARABLE = new Object();
+
+ @Rule
+ public MockitoRule mockitoRule = MockitoJUnit.rule();
+
+ @Mock
+ public IMethods mock;
+
+ /**
+ * Should not throw an {@link NullPointerException}
+ *
+ * @see Bug-ID https://github.com/mockito/mockito/issues/457
+ */
+ @Test
+ public void compareNullArgument() {
+ boolean match = matchesTypeSafe().apply(new LessOrEqual<Integer>(5), null);
+ assertThat(match).isFalse();
+
+ }
+
+ /**
+ * Should not throw an {@link ClassCastException}
+ */
+ @Test
+ public void compareToNonCompareable() {
+ boolean match = matchesTypeSafe().apply(new LessOrEqual<Integer>(5), NOT_A_COMPARABLE);
+ assertThat(match).isFalse();
+ }
+
+ /**
+ * Should not throw an {@link ClassCastException}
+ */
+ @Test
+ public void compareToNull() {
+ boolean match = matchesTypeSafe().apply(new LessOrEqual<Integer>(null), null);
+ assertThat(match).isFalse();
+ }
+
+ /**
+ * Should not throw an {@link ClassCastException}
+ */
+ @Test
+ public void compareToNull2() {
+ boolean match = matchesTypeSafe().apply(Null.NULL, null);
+ assertThat(match).isTrue();
+ }
+
+ /**
+ * Should not throw an {@link ClassCastException}
+ */
+ @Test
+ public void compareToStringVsInt() {
+ boolean match = matchesTypeSafe().apply(new StartsWith("Hello"), 123);
+ assertThat(match).isFalse();
+ }
+
+ @Test
+ public void compareToIntVsString() throws Exception {
+ boolean match = matchesTypeSafe().apply(new LessOrEqual<Integer>(5), "Hello");
+ assertThat(match).isFalse();
+ }
+
+ @Test
+ public void matchesOverloadsMustBeIgnored() {
+ class TestMatcher implements ArgumentMatcher<Integer> {
+ @Override
+ public boolean matches(Integer arg) {
+ return false;
+ }
+
+ @SuppressWarnings("unused")
+ public boolean matches(Date arg) {
+ throw new UnsupportedOperationException();
+ }
+
+ @SuppressWarnings("unused")
+ public boolean matches(Integer arg, Void v) {
+ throw new UnsupportedOperationException();
+ }
+
+ }
+
+ boolean match = matchesTypeSafe().apply(new TestMatcher(), 123);
+ assertThat(match).isFalse();
+ }
+
+ @Test
+ public void matchesWithSubTypeExtendingGenericClass() {
+ abstract class GenericMatcher<T> implements ArgumentMatcher<T> {
+ }
+ class TestMatcher extends GenericMatcher<Integer> {
+ @Override
+ public boolean matches(Integer argument) {
+ return true;
+ }
+ }
+ boolean match = matchesTypeSafe().apply(new TestMatcher(), 123);
+ assertThat(match).isTrue();
+ }
+
+ @Test
+ public void dontMatchesWithSubTypeExtendingGenericClass() {
+ final AtomicBoolean wasCalled = new AtomicBoolean();
+
+ abstract class GenericMatcher<T> implements ArgumentMatcher<T> {
+ }
+ class TestMatcher extends GenericMatcher<Integer> {
+ @Override
+ public boolean matches(Integer argument) {
+ wasCalled.set(true);
+ return true;
+ }
+ }
+ wasCalled.set(false);
+ matchesTypeSafe().apply(new TestMatcher(), 123);
+ assertThat(wasCalled.get()).isTrue();
+
+ wasCalled.set(false);
+ matchesTypeSafe().apply(new TestMatcher(), "");
+ assertThat(wasCalled.get()).isFalse();
+ }
+
+ @Test
+ public void passEveryArgumentTypeIfNoBridgeMethodWasGenerated() {
+ final AtomicBoolean wasCalled = new AtomicBoolean();
+ class GenericMatcher<T> implements ArgumentMatcher<T> {
+ @Override
+ public boolean matches(T argument) {
+ wasCalled.set(true);
+ return true;
+ }
+ }
+
+ wasCalled.set(false);
+ matchesTypeSafe().apply(new GenericMatcher<Integer>(), 123);
+ assertThat(wasCalled.get()).isTrue();
+
+ wasCalled.set(false);
+ matchesTypeSafe().apply(new GenericMatcher<Integer>(), "");
+ assertThat(wasCalled.get()).isTrue();
+ }
+}
diff --git a/src/test/java/org/mockito/internal/util/reflection/FieldInitializerTest.java b/src/test/java/org/mockito/internal/util/reflection/FieldInitializerTest.java
index 38cafecc82..185bfaea17 100644
--- a/src/test/java/org/mockito/internal/util/reflection/FieldInitializerTest.java
+++ b/src/test/java/org/mockito/internal/util/reflection/FieldInitializerTest.java
@@ -6,6 +6,7 @@
import org.junit.Test;
import org.mockito.InjectMocks;
+import org.mockito.Mockito;
import org.mockito.exceptions.base.MockitoException;
import org.mockito.internal.util.reflection.FieldInitializer.ConstructorArgumentResolver;
@@ -156,7 +157,7 @@ public void should_not_fail_if_inner_class_field_is_instantiated() throws Except
@Test
public void can_instantiate_class_with_parameterized_constructor() throws Exception {
- ConstructorArgumentResolver resolver = given(mock(ConstructorArgumentResolver.class).resolveTypeInstances(any(Class[].class)))
+ ConstructorArgumentResolver resolver = given(mock(ConstructorArgumentResolver.class).resolveTypeInstances(any(Class.class)))
.willReturn(new Object[]{null}).getMock();
new FieldInitializer(this, field("noDefaultConstructor"), resolver).initialize();
diff --git a/src/test/java/org/mockitousage/matchers/VarargsTest.java b/src/test/java/org/mockitousage/matchers/VarargsTest.java
new file mode 100644
index 0000000000..6720ca5ff0
--- /dev/null
+++ b/src/test/java/org/mockitousage/matchers/VarargsTest.java
@@ -0,0 +1,341 @@
+package org.mockitousage.matchers;
+
+import static org.junit.Assert.fail;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.ArgumentMatchers.isNotNull;
+import static org.mockito.ArgumentMatchers.isNull;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import org.assertj.core.api.AbstractListAssert;
+import org.assertj.core.api.Assertions;
+import org.assertj.core.api.Condition;
+import org.junit.Ignore;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.ExpectedException;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Captor;
+import org.mockito.Mock;
+import org.mockito.exceptions.verification.junit.ArgumentsAreDifferent;
+import org.mockito.junit.MockitoJUnit;
+import org.mockito.junit.MockitoRule;
+import org.mockitousage.IMethods;
+
+public class VarargsTest {
+
+ @Rule
+ public MockitoRule mockitoRule = MockitoJUnit.rule();
+ @Rule
+ public ExpectedException exception = ExpectedException.none();
+ @Captor
+ private ArgumentCaptor<String> captor;
+ @Mock
+ private IMethods mock;
+
+ private static final Condition<Object> NULL = new Condition<Object>() {
+
+ @Override
+ public boolean matches(Object value) {
+ return value == null;
+ }
+ };
+
+ @Test
+ public void shouldMatchVarArgs_noArgs() {
+ mock.varargs();
+
+ verify(mock).varargs();
+ }
+
+ @Test
+ @Ignore("This test must succeed but is fails currently, see github issue #616")
+ public void shouldMatchEmptyVarArgs_noArgsIsNotNull() {
+ mock.varargs();
+
+ verify(mock).varargs(isNotNull());
+ }
+
+ @Test
+ @Ignore("This test must succeed but is fails currently, see github issue #616")
+ public void shouldMatchEmptyVarArgs_noArgsIsNull() {
+ mock.varargs();
+
+ verify(mock).varargs(isNull());
+ }
+
+ @Test
+ @Ignore("This test must succeed but is fails currently, see github issue #616")
+ public void shouldMatchEmptyVarArgs_noArgsIsNotNullArray() {
+ mock.varargs();
+
+ verify(mock).varargs((String[]) isNotNull());
+ }
+
+ @Test
+ public void shouldMatchVarArgs_oneNullArg_eqNull() {
+ Object arg = null;
+ mock.varargs(arg);
+
+ verify(mock).varargs(eq(null));
+ }
+
+ @Test
+ public void shouldMatchVarArgs_oneNullArg_isNull() {
+ Object arg = null;
+ mock.varargs(arg);
+
+ verify(mock).varargs(isNull());
+ }
+
+ @Test
+ public void shouldMatchVarArgs_nullArrayArg() {
+ Object[] argArray = null;
+ mock.varargs(argArray);
+
+ verify(mock).varargs(isNull());
+ }
+
+ @Test
+ public void shouldnotMatchVarArgs_twoArgsOneMatcher() {
+ mock.varargs("1", "1");
+
+ exception.expectMessage("Argument(s) are different");
+
+ verify(mock).varargs(eq("1"));
+ }
+
+ @Test
+ public void shouldMatchVarArgs_emptyVarArgsOneAnyMatcher() {
+ mock.varargs();
+
+ verify(mock).varargs((String[])any()); // any() -> VarargMatcher
+ }
+
+ @Test
+ public void shouldMatchVarArgs_oneArgsOneAnyMatcher() {
+ mock.varargs(1);
+
+ verify(mock).varargs(any()); // any() -> VarargMatcher
+ }
+
+ @Test
+ public void shouldMatchVarArgs_twoArgsOneAnyMatcher() {
+ mock.varargs(1, 2);
+
+ verify(mock).varargs(any()); // any() -> VarargMatcher
+ }
+
+ @Test
+ public void shouldMatchVarArgs_twoArgsTwoAnyMatcher() {
+ mock.varargs(1, 2);
+
+ verify(mock).varargs(any(), any()); // any() -> VarargMatcher
+ }
+
+ @Test
+ public void shouldMatchVarArgs_twoArgsThreeAnyMatcher() {
+ mock.varargs(1, 2);
+
+ exception.expectMessage("Argument(s) are different");
+
+ verify(mock).varargs(any(), any(), any()); //any() -> VarargMatcher
+ }
+
+ @Test
+ public void shouldMatchVarArgs_oneNullArgument() {
+ mock.varargs("1", null);
+
+ verify(mock).varargs(eq("1"), (String) isNull());
+ }
+
+ @Test
+ public void shouldMatchVarArgs_onebyte() {
+ mock.varargsbyte((byte) 1);
+
+ verify(mock).varargsbyte(eq((byte) 1));
+ }
+
+ @Test
+ public void shouldMatchVarArgs_nullByteArray() {
+ mock.varargsbyte(null);
+
+ verify(mock).varargsbyte((byte[]) isNull());
+ }
+
+ @Test
+ public void shouldMatchVarArgs_emptyByteArray() {
+ mock.varargsbyte();
+
+ verify(mock).varargsbyte();
+ }
+
+ @Test
+ @Ignore
+ public void shouldMatchEmptyVarArgs_emptyArrayIsNotNull() {
+ mock.varargsbyte();
+
+ verify(mock).varargsbyte((byte[]) isNotNull());
+ }
+
+ @Test
+ public void shouldMatchVarArgs_oneArgIsNotNull() {
+ mock.varargsbyte((byte) 1);
+
+ verify(mock).varargsbyte((byte[]) isNotNull());
+ }
+
+ @Test
+ public void shouldCaptureVarArgs_noArgs() {
+ mock.varargs();
+
+ verify(mock).varargs(captor.capture());
+
+ assertThat(captor).isEmpty();
+ }
+
+ @Test
+ public void shouldCaptureVarArgs_oneNullArg_eqNull() {
+ String arg = null;
+ mock.varargs(arg);
+
+ verify(mock).varargs(captor.capture());
+
+ assertThat(captor).areExactly(1, NULL);
+ }
+
+ /**
+ * Relates to Github issue #583 "ArgumentCaptor: NPE when an null array is
+ * passed to a varargs method"
+ */
+ @Test
+ public void shouldCaptureVarArgs_nullArrayArg() {
+ String[] argArray = null;
+ mock.varargs(argArray);
+
+ verify(mock).varargs(captor.capture());
+ assertThat(captor).areExactly(1, NULL);
+ }
+
+ @Test
+ public void shouldCaptureVarArgs_twoArgsOneCapture() {
+ mock.varargs("1", "2");
+
+ verify(mock).varargs(captor.capture());
+
+ assertThat(captor).contains("1", "2");
+ }
+
+ @Test
+ public void shouldCaptureVarArgs_twoArgsTwoCaptures() {
+ mock.varargs("1", "2");
+
+ verify(mock).varargs(captor.capture(), captor.capture());
+
+ assertThat(captor).contains("1", "2");
+ }
+
+ @Test
+ public void shouldCaptureVarArgs_oneNullArgument() {
+ mock.varargs("1", null);
+
+ verify(mock).varargs(captor.capture());
+
+ assertThat(captor).contains("1", (String) null);
+ }
+
+ @Test
+ public void shouldCaptureVarArgs_oneNullArgument2() {
+ mock.varargs("1", null);
+
+ verify(mock).varargs(captor.capture(), captor.capture());
+
+ assertThat(captor).contains("1", (String) null);
+ }
+
+ @Test
+ public void shouldNotCaptureVarArgs_3args2captures() {
+ mock.varargs("1", "2", "3");
+
+ exception.expect(ArgumentsAreDifferent.class);
+
+ verify(mock).varargs(captor.capture(), captor.capture());
+
+ }
+
+ @Test
+ public void shouldCaptureVarArgs_3argsCaptorMatcherMix() {
+ mock.varargs("1", "2", "3");
+
+ verify(mock).varargs(captor.capture(), eq("2"), captor.capture());
+
+ assertThat(captor).containsExactly("1", "3");
+
+ }
+
+ @Test
+ public void shouldNotCaptureVarArgs_3argsCaptorMatcherMix() {
+ mock.varargs("1", "2", "3");
+
+ try {
+ verify(mock).varargs(captor.capture(), eq("X"), captor.capture());
+ fail("The verification must fail, cause the second arg was not 'X' as expected!");
+ } catch (ArgumentsAreDifferent expected) {
+ }
+
+ assertThat(captor).isEmpty();
+
+ }
+
+ @Test
+ public void shouldNotCaptureVarArgs_1args2captures() {
+ mock.varargs("1");
+
+ exception.expect(ArgumentsAreDifferent.class);
+
+ verify(mock).varargs(captor.capture(), captor.capture());
+
+ }
+
+ /**
+ * As of v2.0.0-beta.118 this test fails. Once the github issues:
+ * <ul>
+ * <li>'#584 ArgumentCaptor can't capture varargs-arrays
+ * <li>#565 ArgumentCaptor should be type aware' are fixed this test must
+ * succeed
+ * </ul>
+ *
+ * @throws Exception
+ */
+ @Test
+ @Ignore("Blocked by github issue: #584 & #565")
+ public void shouldCaptureVarArgsAsArray() {
+ mock.varargs("1", "2");
+
+ ArgumentCaptor<String[]> varargCaptor = ArgumentCaptor.forClass(String[].class);
+
+ verify(mock).varargs(varargCaptor.capture());
+
+ assertThat(varargCaptor).containsExactly(new String[] { "1", "2" });
+ }
+
+ @Test
+ public void shouldNotMatchRegualrAndVaraArgs() {
+ mock.varargsString(1, "a","b");
+
+ exception.expect(ArgumentsAreDifferent.class);
+
+ verify(mock).varargsString(1);
+ }
+ @Test
+ public void shouldNotMatchVaraArgs() {
+ when(mock.varargsObject(1, "a","b")).thenReturn("OK");
+
+ Assertions.assertThat(mock.varargsObject(1)).isNull();
+ }
+
+ private static <T> AbstractListAssert<?, ?, T> assertThat(ArgumentCaptor<T> captor) {
+ return Assertions.assertThat(captor.getAllValues());
+ }
+}
\ No newline at end of file
| train | train | 2016-09-29T14:46:49 | "2016-08-23T11:26:41Z" | ChristianSchwarz | train |
mockito/mockito/561_637 | mockito/mockito | mockito/mockito/561 | mockito/mockito/637 | [
"keyword_pr_to_issue",
"timestamp(timedelta=0.0, similarity=0.969093382067285)"
] | be755a3d9e8424e8587857390abbc07001644778 | 5928a703e913b6f17ad927c97fcc1e900d6f44ca | [
"After we branch out `release/2.x` ;)\n",
"Kotlin? We need to discuss it before ;)\n",
"Yes we can discuss it in this issue. I have not looked into Kotlin at all so have no opinion atm. You do?\n",
"There are some limitations in Kotlin scripts. It is highlighted also in the [release notes](https://docs.gradle.org/3.0/release-notes):\n\n> ... we are working intensely to make Gradle Script Kotlin fully production ready by the end of the year ...\n\nIn addition we have quite extensive build logic written in Groovy and I don't know it is worth to rewrite it just to have nicer code completion in Idea for those not very often times where there is something to change.\n",
"Seem decent arguments to not switch to Kotlin yet :+1: \n",
"However gradle 3.0 still allows groovy, so that's not a blocker to switch\n",
"And should \"always\" will:\n\n> Groovy is still the primary build language for Gradle scripts and will **always** be supported\n",
"+1 to keeping groovy build scripts :)\n",
"We cannot do it right now because Gradle 3.0 does not build with java6 and current release is still for java6 :( Let's close and revisit later. We won't forget to bump Gradle :)\n",
"We will switch from Java 6 soon and this issue has not been resolved yet. Therefore reopening to be tracked in waffle.\n"
] | [
"I assume we already moved the baseline java8 so this should be safe. Nice.\n",
"Yup in https://github.com/mockito/mockito/commit/be755a3d9e8424e8587857390abbc07001644778 :smile: \n"
] | "2016-09-17T12:26:53Z" | [
"continuous integration"
] | Update Gradle to 3.0 | Gradle 3.0 is released so we can look into upgrading. Potentially we can rewrite our scripts into Kotlin.
| [
"build.gradle",
"gradle/javadoc.gradle",
"gradle/wrapper/gradle-wrapper.properties",
"gradlew",
"gradlew.bat"
] | [
"build.gradle",
"gradle/javadoc.gradle",
"gradle/wrapper/gradle-wrapper.properties",
"gradlew",
"gradlew.bat"
] | [] | diff --git a/build.gradle b/build.gradle
index b432d9b62c..af1eebc19c 100644
--- a/build.gradle
+++ b/build.gradle
@@ -122,7 +122,7 @@ apply from: 'gradle/release.gradle'
apply from: "gradle/pom.gradle"
task wrapper(type: Wrapper) {
- gradleVersion = '2.14.1'
+ gradleVersion = '3.0'
}
task ciBuild {
diff --git a/gradle/javadoc.gradle b/gradle/javadoc.gradle
index 921589844d..4387c965b1 100644
--- a/gradle/javadoc.gradle
+++ b/gradle/javadoc.gradle
@@ -54,9 +54,7 @@ task mockitoJavadoc(type: Javadoc) {
""".replaceAll(/\r|\n/, ""))
options.stylesheetFile file("src/javadoc/stylesheet.css")
// options.addStringOption('top', 'some html')
- if (JavaVersion.current().isJava8Compatible()) {
- options.addStringOption('Xdoclint:none', '-quiet')
- }
+ options.addStringOption('Xdoclint:none', '-quiet')
doLast {
copy {
diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties
index 69ef29851a..08b5db1824 100644
--- a/gradle/wrapper/gradle-wrapper.properties
+++ b/gradle/wrapper/gradle-wrapper.properties
@@ -1,6 +1,6 @@
-#Fri Aug 19 18:41:31 PDT 2016
+#Sat Sep 17 14:22:48 CEST 2016
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
-distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-bin.zip
+distributionUrl=https\://services.gradle.org/distributions/gradle-3.0-bin.zip
diff --git a/gradlew b/gradlew
index 9d82f78915..27309d9231 100755
--- a/gradlew
+++ b/gradlew
@@ -6,12 +6,30 @@
##
##############################################################################
-# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
-DEFAULT_JVM_OPTS=""
+# Attempt to set APP_HOME
+# Resolve links: $0 may be a link
+PRG="$0"
+# Need this for relative symlinks.
+while [ -h "$PRG" ] ; do
+ ls=`ls -ld "$PRG"`
+ link=`expr "$ls" : '.*-> \(.*\)$'`
+ if expr "$link" : '/.*' > /dev/null; then
+ PRG="$link"
+ else
+ PRG=`dirname "$PRG"`"/$link"
+ fi
+done
+SAVED="`pwd`"
+cd "`dirname \"$PRG\"`/" >/dev/null
+APP_HOME="`pwd -P`"
+cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
+# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+DEFAULT_JVM_OPTS=""
+
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
@@ -30,6 +48,7 @@ die ( ) {
cygwin=false
msys=false
darwin=false
+nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
@@ -40,26 +59,11 @@ case "`uname`" in
MINGW* )
msys=true
;;
+ NONSTOP* )
+ nonstop=true
+ ;;
esac
-# Attempt to set APP_HOME
-# Resolve links: $0 may be a link
-PRG="$0"
-# Need this for relative symlinks.
-while [ -h "$PRG" ] ; do
- ls=`ls -ld "$PRG"`
- link=`expr "$ls" : '.*-> \(.*\)$'`
- if expr "$link" : '/.*' > /dev/null; then
- PRG="$link"
- else
- PRG=`dirname "$PRG"`"/$link"
- fi
-done
-SAVED="`pwd`"
-cd "`dirname \"$PRG\"`/" >/dev/null
-APP_HOME="`pwd -P`"
-cd "$SAVED" >/dev/null
-
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
@@ -85,7 +89,7 @@ location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
-if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
+if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
diff --git a/gradlew.bat b/gradlew.bat
index 5f192121eb..832fdb6079 100644
--- a/gradlew.bat
+++ b/gradlew.bat
@@ -8,14 +8,14 @@
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
-@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
-set DEFAULT_JVM_OPTS=
-
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
+@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+set DEFAULT_JVM_OPTS=
+
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
| null | test | train | 2016-09-17T13:29:57 | "2016-08-16T10:19:28Z" | TimvdLippe | train |
mockito/mockito/521_637 | mockito/mockito | mockito/mockito/521 | mockito/mockito/637 | [
"keyword_pr_to_issue"
] | be755a3d9e8424e8587857390abbc07001644778 | 5928a703e913b6f17ad927c97fcc1e900d6f44ca | [
"This doclet is required to skip generating Javadoc for internal classes. Is there a mention in the Java 9 jdk of this breaking change?\n",
"This seems the corresponding JIRA ticket: https://bugs.openjdk.java.net/browse/JDK-8154399\n",
"I'm on a mobile device so couldn't check much, but the ticket mention a replacement for `com.sun....Standard` with the rewritten javadoc tool (`jdk.javadoc.doclets.StandardDoclet`) I didn't saw yet the `HtmlDocklet` yet it should be there as well.\n",
"I will be taking a stab at this tomorrow after switching to Java 8.\n",
"I think we have to (in jdk9) to move to `StandardDoclet`: http://hg.openjdk.java.net/jdk9/dev/langtools/file/6077dc32728a/src/jdk.javadoc/share/classes/jdk/javadoc/doclets/StandardDoclet.java However, this class does not exist in jdk8 so I am not sure what our options are.\n",
"I think we could have both doclet in [javadoc.gradle](https://www.theguardian.com/lifeandstyle/2016/apr/29/how-to-have-a-great-conversation-with-someone-who-is-going-to-die)\n\n``` java\nif (JavaVersion.current().isJava9Compatible()) {\n options.doclet \"org.mockito.javadoc.Java9JavadocExclude\"\n} else {\n options.doclet \"org.mockito.javadoc.JavadocExclude\"\n}\n```\n\n[Gradle 3 `JavaVersion` javadoc](https://docs.gradle.org/current/javadoc/org/gradle/api/JavaVersion.html)\n",
"@bric3 Yes that was what I implemented at https://github.com/mockito/mockito/pull/639/files#diff-39cbd22b5198600bd49c364c42e0aaa9R17 :)\n",
"Has been fixed in several PRs and the doclet was later removed."
] | [
"I assume we already moved the baseline java8 so this should be safe. Nice.\n",
"Yup in https://github.com/mockito/mockito/commit/be755a3d9e8424e8587857390abbc07001644778 :smile: \n"
] | "2016-09-17T12:26:53Z" | [
"refactoring",
"java-9"
] | Remove com.sun.* references | Currently build with gradle 3.0-milestone-2 fails with:
```
:buildSrc:compileJava/mnt/homeold/szpak/cosie/code/inne/mockito/buildSrc/src/main/java/org/mockito/javadoc/JavadocExclude.java:4: error: package com.sun.tools.doclets.formats.html does not exist
import com.sun.tools.doclets.formats.html.HtmlDoclet;
^
/mnt/homeold/szpak/cosie/code/inne/mockito/buildSrc/src/main/java/org/mockito/javadoc/JavadocExclude.java:20: error: cannot find symbol
return HtmlDoclet.optionLength(var0);
^
symbol: variable HtmlDoclet
location: class JavadocExclude
/mnt/homeold/szpak/cosie/code/inne/mockito/buildSrc/src/main/java/org/mockito/javadoc/JavadocExclude.java:25: error: cannot find symbol
return HtmlDoclet.start((RootDoc) Proxy.newProxyInstance(clz.getClassLoader(), clz.getInterfaces(), new ExcludeHandler(root)));
^
symbol: variable HtmlDoclet
location: class JavadocExclude
/mnt/homeold/szpak/cosie/code/inne/mockito/buildSrc/src/main/java/org/mockito/javadoc/JavadocExclude.java:29: error: cannot find symbol
return HtmlDoclet.validOptions(var0, var1);
^
symbol: variable HtmlDoclet
location: class JavadocExclude
/mnt/homeold/szpak/cosie/code/inne/mockito/buildSrc/src/main/java/org/mockito/javadoc/JavadocExclude.java:33: error: cannot find symbol
return HtmlDoclet.languageVersion();
^
symbol: variable HtmlDoclet
location: class JavadocExclude
Note: /mnt/homeold/szpak/cosie/code/inne/mockito/buildSrc/src/main/java/org/mockito/javadoc/JavadocExclude.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
5 errors
FAILED
```
Related to #520.
| [
"build.gradle",
"gradle/javadoc.gradle",
"gradle/wrapper/gradle-wrapper.properties",
"gradlew",
"gradlew.bat"
] | [
"build.gradle",
"gradle/javadoc.gradle",
"gradle/wrapper/gradle-wrapper.properties",
"gradlew",
"gradlew.bat"
] | [] | diff --git a/build.gradle b/build.gradle
index b432d9b62c..af1eebc19c 100644
--- a/build.gradle
+++ b/build.gradle
@@ -122,7 +122,7 @@ apply from: 'gradle/release.gradle'
apply from: "gradle/pom.gradle"
task wrapper(type: Wrapper) {
- gradleVersion = '2.14.1'
+ gradleVersion = '3.0'
}
task ciBuild {
diff --git a/gradle/javadoc.gradle b/gradle/javadoc.gradle
index 921589844d..4387c965b1 100644
--- a/gradle/javadoc.gradle
+++ b/gradle/javadoc.gradle
@@ -54,9 +54,7 @@ task mockitoJavadoc(type: Javadoc) {
""".replaceAll(/\r|\n/, ""))
options.stylesheetFile file("src/javadoc/stylesheet.css")
// options.addStringOption('top', 'some html')
- if (JavaVersion.current().isJava8Compatible()) {
- options.addStringOption('Xdoclint:none', '-quiet')
- }
+ options.addStringOption('Xdoclint:none', '-quiet')
doLast {
copy {
diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties
index 69ef29851a..08b5db1824 100644
--- a/gradle/wrapper/gradle-wrapper.properties
+++ b/gradle/wrapper/gradle-wrapper.properties
@@ -1,6 +1,6 @@
-#Fri Aug 19 18:41:31 PDT 2016
+#Sat Sep 17 14:22:48 CEST 2016
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
-distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-bin.zip
+distributionUrl=https\://services.gradle.org/distributions/gradle-3.0-bin.zip
diff --git a/gradlew b/gradlew
index 9d82f78915..27309d9231 100755
--- a/gradlew
+++ b/gradlew
@@ -6,12 +6,30 @@
##
##############################################################################
-# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
-DEFAULT_JVM_OPTS=""
+# Attempt to set APP_HOME
+# Resolve links: $0 may be a link
+PRG="$0"
+# Need this for relative symlinks.
+while [ -h "$PRG" ] ; do
+ ls=`ls -ld "$PRG"`
+ link=`expr "$ls" : '.*-> \(.*\)$'`
+ if expr "$link" : '/.*' > /dev/null; then
+ PRG="$link"
+ else
+ PRG=`dirname "$PRG"`"/$link"
+ fi
+done
+SAVED="`pwd`"
+cd "`dirname \"$PRG\"`/" >/dev/null
+APP_HOME="`pwd -P`"
+cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
+# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+DEFAULT_JVM_OPTS=""
+
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
@@ -30,6 +48,7 @@ die ( ) {
cygwin=false
msys=false
darwin=false
+nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
@@ -40,26 +59,11 @@ case "`uname`" in
MINGW* )
msys=true
;;
+ NONSTOP* )
+ nonstop=true
+ ;;
esac
-# Attempt to set APP_HOME
-# Resolve links: $0 may be a link
-PRG="$0"
-# Need this for relative symlinks.
-while [ -h "$PRG" ] ; do
- ls=`ls -ld "$PRG"`
- link=`expr "$ls" : '.*-> \(.*\)$'`
- if expr "$link" : '/.*' > /dev/null; then
- PRG="$link"
- else
- PRG=`dirname "$PRG"`"/$link"
- fi
-done
-SAVED="`pwd`"
-cd "`dirname \"$PRG\"`/" >/dev/null
-APP_HOME="`pwd -P`"
-cd "$SAVED" >/dev/null
-
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
@@ -85,7 +89,7 @@ location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
-if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
+if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
diff --git a/gradlew.bat b/gradlew.bat
index 5f192121eb..832fdb6079 100644
--- a/gradlew.bat
+++ b/gradlew.bat
@@ -8,14 +8,14 @@
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
-@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
-set DEFAULT_JVM_OPTS=
-
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
+@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+set DEFAULT_JVM_OPTS=
+
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
| null | train | train | 2016-09-17T13:29:57 | "2016-07-30T22:42:29Z" | szpak | train |
mockito/mockito/633_641 | mockito/mockito | mockito/mockito/633 | mockito/mockito/641 | [
"keyword_pr_to_issue"
] | 5928a703e913b6f17ad927c97fcc1e900d6f44ca | 88329aa20973fdc71cb2816139f165148587e0ac | [
"P.S. @szczepiq if you still want to contribute to Mockito that is of course possible too. We are just wondering what the status is :) (if you decide to stay, we also have to invite you for our Slack, which I need your email for)\n",
"I haven't done much for 2.x. I'm comfortable with not being on the list right now. Maybe with 3.x I would have bigger contribution to the project.\n\nI'm against removing Szczepan from the list. He created this project and he deserves to be on the developers list forever. What's more Szczepan currently is quite active, so maybe he will change his mind to leave the project :).\n\nAt the worst I would change developer to former-developer, founder or something like that.\n",
"Yeah the same with me in terms of 2.x. I did close to nothing. I fully agree with @szpak about Szczepan.\n",
"@TimvdLippe, the list can be updated in \"pom.gradle\". I don't see good reasons why we should remove people from this list. All former and current team members should happily remain there, including @szpak and @marcingrzejszczak :)\n\nI'll let you know when I step down completely, not just yet ;) If I become inactive due to other priorities the team should move forward with growing and improving Mockito.\n",
"@szczepiq Yes I agree with the others to not remove people so I submitted #641 which does not remove anyone from the list, only add them :smile: \n"
] | [
"If you like adventures, we could add more info to every developer (for example, github, twitter, blog, etc.)\n"
] | "2016-09-17T15:30:19Z" | [] | Update core dev team in gradle | For example https://mvnrepository.com/artifact/org.mockito/mockito-core/2.1.0-RC.1 only lists @bric3 and @szczepiq. We need to include all @mockito/developers e.g. @timvdlippe, @raphw, @marcingrzejszczak and @szpak
@szczepiq For the 3.0.0-beta.1 should we remove you from the list or what is the expected timeline for you?
| [
"build.gradle",
"gradle/pom.gradle"
] | [
"build.gradle",
"gradle/pom.gradle"
] | [] | diff --git a/build.gradle b/build.gradle
index af1eebc19c..33f03bff72 100644
--- a/build.gradle
+++ b/build.gradle
@@ -119,7 +119,7 @@ publishing {
}
apply from: 'gradle/release.gradle'
-apply from: "gradle/pom.gradle"
+apply from: 'gradle/pom.gradle'
task wrapper(type: Wrapper) {
gradleVersion = '3.0'
diff --git a/gradle/pom.gradle b/gradle/pom.gradle
index dddb22715b..faa50e7073 100644
--- a/gradle/pom.gradle
+++ b/gradle/pom.gradle
@@ -1,6 +1,6 @@
publishing.publications.all {
//TODO github profile?
- def devs = ["szczepiq:Szczepan Faber", "bric3:Brice Dutheil"]
+ def devs = ['szczepiq:Szczepan Faber', 'bric3:Brice Dutheil', 'raphw:Rafael Winterhalter', 'TimvdLippe:Tim van der Lippe']
pom.withXml {
def root = asNode()
@@ -16,13 +16,22 @@ publishing.publications.all {
root.appendNode('scm').appendNode('url', 'http://github.com/mockito/mockito')
+ def issues = root.appendNode('issueManagement')
+ issues.appendNode('url', 'https://github.com/mockito/mockito/issues')
+ issues.appendNode('system', 'GitHub issues')
+
+ def ci = root.appendNode('ciManagement')
+ ci.appendNode('url', 'https://travis-ci.org/mockito/mockito')
+ ci.appendNode('system', 'TravisCI')
+
def developers = root.appendNode('developers')
devs.each {
- def split = it.split(":")
+ def split = it.split(':')
assert split.length == 2
def d = developers.appendNode('developer')
d.appendNode('id', split[0])
d.appendNode('name', split[1])
+ d.appendNode('roles').appendNode('role', 'Core developer')
}
}
}
| null | train | train | 2016-09-17T16:55:06 | "2016-09-12T12:02:50Z" | TimvdLippe | train |