Close

Mockito - Argument Matchers Example

[Last Updated: Aug 11, 2020]

Following example shows how to use static methods of ArgumentMatchers (tutorial).

Examples

Example Project

package com.logicbig.example;

import java.util.Collection;

public interface MyService {
  public int doSomething(String taskName, Collection<?> inputs);

  public default int doSomething(int arg) {
      return arg + 10;
  }
}
package com.logicbig.example;

import java.math.BigDecimal;
import java.sql.SQLOutput;
import java.util.Arrays;

public class MyProcessor {
  private MyService myService;

  public MyProcessor(MyService myService) {
      this.myService = myService;
  }

  public String process() {
      int returnInteger = myService.doSomething("my-process-task", Arrays.asList(1, 3, 5));
      return String.format("My Integer is: " + returnInteger);
  }

  public String process2(){
      int returnInteger = myService.doSomething(10);
      return String.format("My Integer is: " + returnInteger);
  }
}

Using ArgumentMatchers

package com.logicbig.example;

import org.junit.Assert;
import org.junit.Test;
import org.mockito.ArgumentMatchers;
import org.mockito.Mockito;

public class ProcessorTest {

  @Test
  public void processTest() {
      MyService myService = Mockito.mock(MyService.class);
      Mockito.when(
              myService.doSomething(ArgumentMatchers.anyString(), ArgumentMatchers.anyCollection())
      ).thenReturn(10);
      MyProcessor myProcessor = new MyProcessor(myService);
      String returnedValue = myProcessor.process();
      Assert.assertEquals(returnedValue, "My Integer is: 10");
  }
}
D:\example-projects\mockito\argument-matchers\argument-matcher-examples>mvn test -Dtest="ProcessorTest"
[INFO] Scanning for projects...
[INFO]
[INFO] -----------< com.logicbig.example:argument-matcher-examples >-----------
[INFO] Building argument-matcher-examples 1.0-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ argument-matcher-examples ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:compile (default-compile) @ argument-matcher-examples ---
[INFO] Changes detected - recompiling the module!
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ argument-matcher-examples ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:testCompile (default-testCompile) @ argument-matcher-examples ---
[INFO] Changes detected - recompiling the module!
[INFO]
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ argument-matcher-examples ---

-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.logicbig.example.ProcessorTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.778 sec

Results :

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0

[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 5.328 s
[INFO] Finished at: 2020-05-28T01:05:27-05:00
[INFO] ------------------------------------------------------------------------

In above example, anyString() and anyCollection() can be replaced with any() methods

package com.logicbig.example;

import org.junit.Assert;
import org.junit.Test;
import org.mockito.ArgumentMatchers;
import org.mockito.Mockito;

public class ProcessorTest2 {

  @Test
  public void processTest() {
      MyService myService = Mockito.mock(MyService.class);
      Mockito.when(
              myService.doSomething(ArgumentMatchers.any(), ArgumentMatchers.any())
      ).thenReturn(10);
      MyProcessor myProcessor = new MyProcessor(myService);
      String returnedValue = myProcessor.process();
      Assert.assertEquals(returnedValue, "My Integer is: 10");
  }
}
D:\example-projects\mockito\argument-matchers\argument-matcher-examples>mvn test -Dtest="ProcessorTest2"
[INFO] Scanning for projects...
[INFO]
[INFO] -----------< com.logicbig.example:argument-matcher-examples >-----------
[INFO] Building argument-matcher-examples 1.0-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ argument-matcher-examples ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:compile (default-compile) @ argument-matcher-examples ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ argument-matcher-examples ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:testCompile (default-testCompile) @ argument-matcher-examples ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ argument-matcher-examples ---

-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.logicbig.example.ProcessorTest2
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.688 sec

Results :

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0

[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 3.505 s
[INFO] Finished at: 2020-05-28T01:07:03-05:00
[INFO] ------------------------------------------------------------------------

Which one should we use any() or anyString()?

It's preferable to more specific methods (e.g. anyString()) than any() method, that's because it's more readable and secondly any() method can throw NullPointerException in some cases. For example NullPointerException is thrown if try to auto-unbox a null primitive value. For example:

package com.logicbig.example;

import org.junit.Assert;
import org.junit.Test;
import org.mockito.ArgumentMatchers;
import org.mockito.Mockito;
import java.math.BigDecimal;

public class ProcessorTest3 {

  @Test
  public void processTest() {
      MyService myService = Mockito.mock(MyService.class);
      Mockito.when(myService.doSomething(ArgumentMatchers.any())).thenReturn(5);
      MyProcessor myProcessor = new MyProcessor(myService);
      String returnedValue = myProcessor.process();
      Assert.assertEquals(returnedValue, "My Integer is: 0");
  }
}
D:\example-projects\mockito\argument-matchers\argument-matcher-examples>mvn test -Dtest="ProcessorTest3"
[INFO] Scanning for projects...
[INFO]
[INFO] -----------< com.logicbig.example:argument-matcher-examples >-----------
[INFO] Building argument-matcher-examples 1.0-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ argument-matcher-examples ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:compile (default-compile) @ argument-matcher-examples ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ argument-matcher-examples ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:testCompile (default-testCompile) @ argument-matcher-examples ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ argument-matcher-examples ---

-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.logicbig.example.ProcessorTest3
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.772 sec <<< FAILURE!
processTest(com.logicbig.example.ProcessorTest3) Time elapsed: 0.685 sec <<< ERROR!
java.lang.NullPointerException
at com.logicbig.example.ProcessorTest3.processTest(ProcessorTest3.java:14)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:567)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)
at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:252)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:141)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:112)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:567)
at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189)
at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165)
at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85)
at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:115)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:75)


Results :

Tests in error:
processTest(com.logicbig.example.ProcessorTest3)

Tests run: 1, Failures: 0, Errors: 1, Skipped: 0

[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 3.553 s
[INFO] Finished at: 2020-05-28T01:11:54-05:00
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12.4:test (default-test) on project argument-matcher-examples: There are test failures.
[ERROR]
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException

Fixing above error by using anyInt() instead of any():

package com.logicbig.example;

import org.junit.Assert;
import org.junit.Test;
import org.mockito.ArgumentMatchers;
import org.mockito.Mockito;

public class ProcessorTest4 {

  @Test
  public void processTest() {
      MyService myService = Mockito.mock(MyService.class);
      Mockito.when(myService.doSomething(ArgumentMatchers.anyInt())).thenReturn(5);
      MyProcessor myProcessor = new MyProcessor(myService);
      String returnedValue = myProcessor.process2();
      Assert.assertEquals(returnedValue, "My Integer is: 5");
  }
}
D:\example-projects\mockito\argument-matchers\argument-matcher-examples>mvn test -Dtest="ProcessorTest4"
[INFO] Scanning for projects...
[INFO]
[INFO] -----------< com.logicbig.example:argument-matcher-examples >-----------
[INFO] Building argument-matcher-examples 1.0-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ argument-matcher-examples ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:compile (default-compile) @ argument-matcher-examples ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ argument-matcher-examples ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:testCompile (default-testCompile) @ argument-matcher-examples ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ argument-matcher-examples ---

-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.logicbig.example.ProcessorTest4
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.711 sec

Results :

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0

[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 7.595 s
[INFO] Finished at: 2020-05-28T01:15:04-05:00
[INFO] ------------------------------------------------------------------------

Example Project

Dependencies and Technologies Used:

  • mockito-core 3.3.3: Mockito mock objects library core API and implementation.
  • junit 4.13: JUnit is a unit testing framework for Java, created by Erich Gamma and Kent Beck.
  • JDK 8
  • Maven 3.5.4

Mockito - Argument Matcher examples Select All Download
  • argument-matcher-examples
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • MyProcessor.java
        • test
          • java
            • com
              • logicbig
                • example

    See Also