• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2007 Mockito contributors
3  * This program is made available under the terms of the MIT License.
4  */
5 package org.mockitousage.configuration;
6 
7 import java.lang.annotation.Retention;
8 import java.lang.annotation.RetentionPolicy;
9 import java.lang.annotation.Target;
10 import java.lang.reflect.Field;
11 import java.lang.reflect.Modifier;
12 import java.util.Set;
13 import org.junit.Test;
14 import org.mockito.Mockito;
15 import org.mockito.configuration.MockitoConfiguration;
16 import org.mockito.internal.configuration.InjectingAnnotationEngine;
17 import org.mockitousage.IMethods;
18 import org.mockitoutil.TestBase;
19 
20 import static java.lang.annotation.ElementType.FIELD;
21 import static org.junit.Assert.assertEquals;
22 import static org.mockito.Mockito.verify;
23 
24 
25 /**
26  * @see MockitoConfiguration#getAnnotationEngine() for the custom smartmock injection engine
27  */
28 public class CustomizedAnnotationForSmartMockTest extends TestBase {
29 
30     @SmartMock IMethods smartMock;
31 
32     @Test
shouldUseCustomAnnotation()33     public void shouldUseCustomAnnotation() {
34         assertEquals("SmartMock should return empty String by default", "", smartMock.simpleMethod(1));
35         verify(smartMock).simpleMethod(1);
36     }
37 
38     @Target({FIELD })
39     @Retention(RetentionPolicy.RUNTIME)
40     public @interface SmartMock {}
41 
42     public static class CustomInjectingAnnotationEngine extends InjectingAnnotationEngine {
43         @Override
onInjection(Object testClassInstance, Class<?> clazz, Set<Field> mockDependentFields, Set<Object> mocks)44         protected void onInjection(Object testClassInstance, Class<?> clazz, Set<Field> mockDependentFields, Set<Object> mocks) {
45             for (Field field : clazz.getDeclaredFields()) {
46                 if (field.isAnnotationPresent(SmartMock.class)) {
47                     field.setAccessible(true);
48                     try {
49                         field.set(Modifier.isStatic(field.getModifiers()) ? null : testClassInstance, Mockito.mock(field.getType(), Mockito.RETURNS_SMART_NULLS));
50                     } catch (Exception exception) {
51                         throw new AssertionError(exception.getMessage());
52                     }
53                 }
54             }
55         }
56     }
57 }
58