1 package com.atlassian.plugins.rest.common.util;
2
3 import org.junit.Rule;
4 import org.junit.Test;
5 import org.mockito.Mock;
6 import org.mockito.junit.MockitoJUnit;
7 import org.mockito.junit.MockitoRule;
8
9 import java.lang.annotation.Annotation;
10 import java.lang.reflect.AnnotatedElement;
11
12 import static org.junit.Assert.assertNotNull;
13 import static org.junit.Assert.assertNull;
14 import static org.mockito.Mockito.doReturn;
15 import static org.mockito.Mockito.mock;
16 import static org.mockito.Mockito.when;
17
18 @SuppressWarnings("unchecked")
19 public class ReflectionUtilsTest {
20 @Rule
21 public final MockitoRule mockitoRule = MockitoJUnit.rule();
22
23 @Mock
24 private AnnotatedElement element;
25
26 @Test
27 public void testGetAnnotationWithAnnotationPresent() {
28 setAnnotationsOnElement(Rule.class, TestAnnotation.class, Mock.class);
29 assertNotNull(ReflectionUtils.getAnnotation(TestAnnotation.class, element));
30 }
31
32 @Test
33 public void testGetAnnotationWithAnnotationNotPresent() {
34 setAnnotationsOnElement(Rule.class, Mock.class);
35 assertNull(ReflectionUtils.getAnnotation(TestAnnotation.class, element));
36 }
37
38 @Test
39 public void testGetAnnotationWithNoAnnotationsPresent() {
40 setAnnotationsOnElement();
41 assertNull(ReflectionUtils.getAnnotation(TestAnnotation.class, element));
42 }
43
44 private void setAnnotationsOnElement(Class<? extends Annotation>... annotationTypes) {
45 final Annotation[] annotations = new Annotation[annotationTypes.length];
46 for (int i = 0; i < annotationTypes.length; i++) {
47 Annotation a = mock(annotationTypes[i]);
48 doReturn(annotationTypes[i]).when(a).annotationType();
49 annotations[i] = a;
50 }
51 when(element.getAnnotations()).thenReturn(annotations);
52 }
53
54 private @interface TestAnnotation {
55 }
56 }