1

I have an annotation,

@Retention(RetentionPolicy.RUNTIME) 
@Target(value={ElementType.METHOD, ElementType.TYPE})
public @interface JobLoggable {
    JobType jobType();
    JobDomain domain();
    JobStatus jobInitialStatus();
}

which I apply to my class

@JobLoggable
public class Process {
    public void doSomething() {
        Annotation[] annotations = this.getClass().getAnnotations();
        Assert.assert(annotations.length == 1);
    }
}

In my test, I spy on it (not mock it, though it shouldn't matter):

public class Test {
    @Test
    public void test() {
        Process process = Mockito.spy(Process.class);
        //spy on some internal methods, capture their return values
        process.doSomething();
    }
}

Sadly there are no annotations returned by this.getClass().getAnnotations(). When I look at what class the instance is, it is: Process$$EnhancerByMockitoWithCGLIB$$3db5579b

It isn't a true Process class. I suppose this is why it fails to retrieve the annotations.

Maybe there is some trick around this. Any ideas? Thanks guys.

I already tried to mock getClass() on the process instance but it is final, so it cannot be mocked.

Calicoder
  • 1,322
  • 1
  • 19
  • 37

1 Answers1

0

I was stumped by this problem until i read this documentation:

38. Meta data and generic type retention (Since 2.1.0)

Mockito now preserves annotations on mocked methods and types as well as generic meta data. Previously, a mock type did not preserve annotations on types unless they were explicitly inherited and never retained annotations on methods. As a consequence, the following conditions now hold true:

Looks like the solution is simply updating to >2.1.0 of mockito. I was using 1.10.19. If you're using Java 7, you might have to upgrade to Java 8 though.

Calicoder
  • 1,322
  • 1
  • 19
  • 37