mockito/mockito · error · MockitoException

This combination of annotations is not permitted on a single

Error message

This combination of annotations is not permitted on a single field:
@${annotationOne} and @${annotationTwo}

What it means

InjectMocksScanner scans test class fields for @InjectMocks and asserts that an @InjectMocks field carries none of a set of incompatible annotations. If it finds one, it throws unsupportedCombinationOfAnnotations(annotationName, "InjectMocks"): 'This combination of annotations is not permitted on a single field: @X and @InjectMocks'. @InjectMocks marks the target of injection and cannot double as a mock/spy/captor.

Source

Thrown at mockito-core/src/main/java/org/mockito/internal/configuration/injection/scanner/InjectMocksScanner.java:65

    @SuppressWarnings("unchecked")
    private Set<Field> scan() {
        Set<Field> mockDependentFields = new HashSet<>();
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            if (null != field.getAnnotation(InjectMocks.class)) {
                assertNoAnnotations(field, Mock.class, Captor.class);
                mockDependentFields.add(field);
            }
        }

        return mockDependentFields;
    }

    private static void assertNoAnnotations(
            Field field, Class<? extends Annotation>... annotations) {
        for (Class<? extends Annotation> annotation : annotations) {
            if (field.isAnnotationPresent(annotation)) {
                throw unsupportedCombinationOfAnnotations(
                        annotation.getSimpleName(), InjectMocks.class.getSimpleName());
            }
        }
    }
}

View on GitHub (pinned to 5a676bcd9e)

Solutions

  1. Keep only @InjectMocks on the field and let Mockito instantiate it
  2. Annotate dependencies with @Mock and leave the system-under-test with just @InjectMocks
  3. If you need a real instance, instantiate it manually and drop both annotations

Example fix

// before
@Mock
@InjectMocks private Service svc;
// after
@InjectMocks private Service svc;
Defensive patterns

Strategy: validation

Validate before calling

if (field.isAnnotationPresent(InjectMocks.class) &&
    (field.isAnnotationPresent(Mock.class) || field.isAnnotationPresent(Spy.class) || field.isAnnotationPresent(Captor.class)))
    throw new IllegalStateException("@InjectMocks must be the only mockito annotation on " + field.getName());

Prevention

When it happens

Trigger: Declaring a field with @InjectMocks together with @Mock, @Spy, @Captor (whatever annotations are passed to assertNoAnnotations) and running openMocks/annotation processing via scan().

Common situations: Misunderstanding @InjectMocks as a flavor of @Mock and stacking both; auto-adding annotations via IDE templates; copy-paste between test classes.

Related errors


AI-assisted analysis of mockito/mockito@5a676bcd9e (2026-09-05). Data as JSON: /api/errors/9eccc54ac248164e. Report an issue: GitHub.