Uploaded image for project: 'Rules Repository'
  1. Rules Repository
  2. RSPEC-6068

Call to Mockito method "verify", "when" or "given" should be simplified

    XMLWordPrintable

    Details

    • Type: Code Smell Detection
    • Status: Active
    • Resolution: Unresolved
    • Labels:
    • Message:
      Remove this/these useless "eq" invocation and directly use the value
    • Highlighting:
      Hide

      primary: first "eq()"
      secondary: other subsequent "eq()" in the rest of the method invocation

      Show
      primary: first "eq()" secondary: other subsequent "eq()" in the rest of the method invocation
    • Default Severity:
      Minor
    • Impact:
      Low
    • Likelihood:
      Low
    • Default Quality Profiles:
      Sonar way
    • Covered Languages:
      Java
    • Irrelevant for Languages:
      ABAP, APEX, C#, C, C++, Cobol, CSS, Flex, Go, HTML, JavaScript, Kotlin, Objective-C, PHP, PL/I, PL/SQL, Python, RPG, Ruby, Rust, Scala, Solidity, Swift, T-SQL, TypeScript, VB.Net, VB6, XML
    • Remediation Function:
      Constant/Issue
    • Constant Cost:
      2min
    • Analysis Level:
      Semantic Analysis
    • Analysis Scope:
      Test Sources

      Description

      Mockito provides argument matchers for flexibly stubbing or verifying method calls.

      Mockito.verify(), Mockito.when(), Stubber.when() and BDDMockito.given() each have overloads with and without argument matchers.

      However, the default matching behavior (i.e. without argument matchers) uses equals(). If only the matcher org.mockito.ArgumentMatchers.eq() is used, the call is equivalent to the call without matchers, i.e. the eq() is not necessary and can be omitted. The resulting code is shorter and easier to read.

      Noncompliant Code Example

      @Test
      public void myTest() {
        given(foo.bar(eq(v1), eq(v2), eq(v3))).willReturn(null);   // Noncompliant
        when(foo.baz(eq(v4), eq(v5))).thenReturn("foo");   // Noncompliant
        doThrow(new RuntimeException()).when(foo).quux(eq(42));    // Noncompliant
        verify(foo).bar(eq(v1), eq(v2), eq(v3));   // Noncompliant
      }
      

      Compliant Solution

      @Test
      public void myTest() {
        given(foo.bar(v1, v2, v3)).willReturn(null);
        when(foo.baz(v4, v5)).thenReturn("foo");
        doThrow(new RuntimeException()).when(foo).quux(42);
        verify(foo).bar(v1, v2, v3);
      }
      

      See

      • Mockito documentation - argument matchers
      • S6073 - Mockito argument matchers should be used on all parameters

        Attachments

          Issue Links

            Activity

              People

              Assignee:
              Unassigned Unassigned
              Reporter:
              michael.gumowski Michael Gumowski
              Votes:
              0 Vote for this issue
              Watchers:
              1 Start watching this issue

                Dates

                Created:
                Updated: