Skip to content

Mockito mock of interfaces lost annotation information #2640

@udengaardandersent-ELS

Description

@udengaardandersent-ELS

I see some different behaviour after updating mockito, and I think it's a bug.
See code below - the test fails because the mocked interface has lost the expected annotation.

Making mocks of classes, keeps the annotation information.
Making mocks of interfaces, annotation information is lost.

Junit version: junit:junit:4.13.2
mockito version: org.mockito:mockito-core:4.5.1
openJDK 11

package com.company;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import org.hamcrest.MatcherAssert;
import org.hamcrest.core.IsNull;
import org.junit.Test;
import org.mockito.Mockito;

public class TestAnnotation {

	@Retention(RetentionPolicy.RUNTIME)
	@Target(ElementType.TYPE)
	public @interface SomeAnnotation {
	}

	@SomeAnnotation
	public class SomeClass {
	}

	@SomeAnnotation
	public interface SomeInterface {
	}

	@Test
	public void testAnnotation() {
		SomeClass someClass = new SomeClass();
		MatcherAssert.assertThat(someClass.getClass().getAnnotation(SomeAnnotation.class), IsNull.notNullValue());
		SomeClass spyOnSomeClass = Mockito.spy(someClass);
		MatcherAssert.assertThat(spyOnSomeClass.getClass().getAnnotation(SomeAnnotation.class), IsNull.notNullValue());
		SomeClass someClassMock = Mockito.mock(SomeClass.class);
		MatcherAssert.assertThat(someClassMock.getClass().getAnnotation(SomeAnnotation.class), IsNull.notNullValue());

		MatcherAssert.assertThat(SomeInterface.class.getAnnotation(SomeAnnotation.class), IsNull.notNullValue());
		SomeInterface someInterfaceMock = Mockito.mock(SomeInterface.class);
		MatcherAssert.assertThat(someInterfaceMock.getClass().getAnnotation(SomeAnnotation.class), IsNull.notNullValue());
	}
}

The test works on previous versions of mockito like, 4.4.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions