Mocking Annotations

Mocking annotations allow fine grained control over what mocking should be preferred when testing.

Using @InTestsMock

Perhaps you have a method that Diffblue Cover would ordinarily test using an Integer but you'd prefer to see it tested using Mockito.mock(..). In this case you could annotate the method (or class, or package) to recommend mocking Number:

public class ClassUnderTest {
  @InTestsMock(Number.class)
  public static String methodUnderTest(Number number) {
    return String.valueOf(number.intValue());
  }
}

Conversely, if Diffblue Cover normally does mock a particular class, and you have a particular location where it shouldn't be then you can forbid it:

public class ClassUnderTest { 
  @InTestsMock(value = Number.class, decision = MockDecision.FORBIDDEN)
  public static String methodUnderTest(Number number) {
    return String.valueOf(number.intValue());
  }
}

Note that using @InTestsMock has the same effect as, and can be overridden by, Cover CLI command line options:

dcover create --mock ClassToMock --disable-mock-inputs ClassToForbidMocking

Using @InTestsMockConstruction

Perhaps you have a method that Diffblue Cover is unable to test, and you think it could make more progress using Mockito.mockConstruction(Random.class). In this case you could annotate the method (or class, or package) to recommend mocking construction of Random:

public class ClassUnderTest {
  @InTestsMockConstruction(Random.class)
  public static int methodUnderTest() {
    return new Random().nextInt();
  }
}

Note that using @InTestsMockConstruction has the same effect as, and can be overridden by, Cover CLI command line option:

dcover create --mock-construction ClassToMockConstruction

Using @InTestsMockStatic

Perhaps you have a method that Diffblue Cover is unable to test, and you think it could make more progress using Mockito.mockStatic(UUID.class). In this case you could annotate the method (or class, or package) to recommend mocking static methods of UUID:

public class ClassUnderTest {
  @InTestsMockStatic(UUID.class)
  public static Path methodUnderTest() {
    return Paths.get(UUID.randomUUID() + ".zip");
  }
}

Note that using @InTestsMockStatic has the same effect as, and can be overridden by, Cover CLI command line option:

dcover create --mock-static ClassToMockStatic

Last updated