summaryrefslogtreecommitdiffstats
path: root/tests/com/google/android/testing/mocking/UsesMocksProcessorTest.java
blob: 0b8961b8137e8a61db9c81a62e63ea3df9057b2c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
/*
 * Copyright 2010 Google Inc.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.google.android.testing.mocking;

import javassist.CannotCompileException;

import junit.framework.TestCase;

import org.easymock.EasyMock;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.processing.Filer;
import javax.annotation.processing.Messager;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.AnnotationValue;
import javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.type.TypeVisitor;
import javax.tools.JavaFileObject;

/**
 * @author swoodward@google.com (Stephen Woodward)
 */
public class UsesMocksProcessorTest extends TestCase {

  private Set<? extends Element> getAnnotatedElementsSet(Class<?>... classes) {
    Set<Element> set = new HashSet<Element>();
    for (Class<?> clazz : classes) {
      set.add(getMockElement(clazz));
    }
    return set;
  }

  @SuppressWarnings("unchecked")
  private Element getMockElement(Class<?> clazz) {
    Element mockElement = EasyMock.createNiceMock(Element.class);
    EasyMock.expect(mockElement.getAnnotationMirrors()).andReturn(getMockAnnotationMirrors(clazz))
        .anyTimes();
    EasyMock.replay(mockElement);
    return mockElement;
  }

  @SuppressWarnings("unchecked")
  private List getMockAnnotationMirrors(Class<?> clazz) {
    List<AnnotationMirror> mockMirrorList = new ArrayList<AnnotationMirror>();
    AnnotationMirror mockMirror = EasyMock.createNiceMock(AnnotationMirror.class);
    EasyMock.expect(mockMirror.getAnnotationType()).andReturn(getMockAnnotationType()).anyTimes();
    EasyMock.expect(mockMirror.getElementValues()).andReturn(getMockElementValuesMap(clazz))
        .anyTimes();
    EasyMock.replay(mockMirror);
    mockMirrorList.add(mockMirror);
    return mockMirrorList;
  }

  @SuppressWarnings("unchecked")
  private Map getMockElementValuesMap(Class<?> clazz) {
    Map mockValuesMap = new HashMap();
    mockValuesMap.put(getMockExecutableElement(), getMockAnnotationValue(clazz));
    return mockValuesMap;
  }

  private AnnotationValue getMockAnnotationValue(Class<?> clazz) {
    AnnotationValue mockValue = EasyMock.createMock(AnnotationValue.class);
    EasyMock.expect(mockValue.getValue()).andReturn(
        Arrays.asList(new String[] {clazz.getName() + ".class"})).anyTimes();
    EasyMock.replay(mockValue);
    return mockValue;
  }

  private ExecutableElement getMockExecutableElement() {
    ExecutableElement mockElement = EasyMock.createNiceMock(ExecutableElement.class);
    EasyMock.replay(mockElement);
    return mockElement;
  }

  private DeclaredType getMockAnnotationType() {
    return new DeclaredType() {
      @Override
      public String toString() {
        return UsesMocks.class.getName();
      }

      @Override
      public Element asElement() {
        return null;
      }

      @Override
      public TypeMirror getEnclosingType() {
        return null;
      }

      @Override
      public List<? extends TypeMirror> getTypeArguments() {
        return null;
      }

      @Override
      public <R, P> R accept(TypeVisitor<R, P> v, P p) {
        return null;
      }

      @Override
      public TypeKind getKind() {
        return null;
      }
    };
  }

  private UsesMocksProcessor getProcessor() {
    return getProcessor(getMockProcessingEnvironment());
  }

  private UsesMocksProcessor getProcessor(ProcessingEnvironment processingEnv) {
    UsesMocksProcessor processor = new UsesMocksProcessor();
    processor.init(processingEnv);
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    processor.logger = new ProcessorLogger(outputStream, processingEnv);
    return processor;
  }

  private ProcessingEnvironment getMockProcessingEnvironment(Filer mockFiler) {
    ProcessingEnvironment mockEnvironment = EasyMock.createNiceMock(ProcessingEnvironment.class);
    EasyMock.expect(mockEnvironment.getMessager()).andReturn(getMockMessager()).anyTimes();
    EasyMock.expect(mockEnvironment.getFiler()).andReturn(mockFiler).anyTimes();
    EasyMock.expect(mockEnvironment.getOptions()).andReturn(getMockOptions()).anyTimes();
    EasyMock.replay(mockEnvironment);
    return mockEnvironment;
  }

  private Map<String, String> getMockOptions() {
    Map<String, String> map = new HashMap<String, String>();
    map.put("bin_dir", ".");
    map.put("logfile", "logfile");
    return map;
  }

  private ProcessingEnvironment getMockProcessingEnvironment() {
    return getMockProcessingEnvironment(getMockFiler());
  }

  private Messager getMockMessager() {
    Messager mockMessager = EasyMock.createNiceMock(Messager.class);
    EasyMock.replay(mockMessager);
    return mockMessager;
  }

  private Filer getMockFiler() {
    try {
      return getMockFiler(getMockFileObject());
    } catch (IOException e) {
      // Can't happen
      throw new RuntimeException(e);
    }
  }

  private Filer getMockFiler(JavaFileObject mockFileObject) {
    Filer mockFiler = EasyMock.createNiceMock(Filer.class);
    try {
      EasyMock.expect(mockFiler.createClassFile((CharSequence) EasyMock.anyObject())).andReturn(
          mockFileObject).anyTimes();
    } catch (IOException e) {
      // Can't happen
      throw new RuntimeException(e);
    }
    EasyMock.replay(mockFiler);
    return mockFiler;
  }

  private JavaFileObject getMockFileObject() throws IOException {
    return getMockFileObject(new ByteArrayOutputStream());
  }

  private JavaFileObject getMockFileObject(OutputStream outStream) throws IOException {
    JavaFileObject mockFileObject = EasyMock.createNiceMock(JavaFileObject.class);
    EasyMock.expect(mockFileObject.openOutputStream()).andReturn(outStream).anyTimes();
    EasyMock.replay(mockFileObject);
    return mockFileObject;
  }

  private RoundEnvironment getMockRoundEnvironment(Set<? extends Element> elementsWithAnnotation) {
    return getMockRoundEnvironment(elementsWithAnnotation, false);
  }

  @SuppressWarnings("unchecked")
  private RoundEnvironment getMockRoundEnvironment(Set<? extends Element> elementsWithAnnotation,
      boolean finishedProcessing) {
    RoundEnvironment mockEnv = EasyMock.createNiceMock(RoundEnvironment.class);
    EasyMock.expect(mockEnv.getElementsAnnotatedWith(UsesMocks.class)).andReturn(
        (Set) elementsWithAnnotation).anyTimes();
    EasyMock.expect(mockEnv.processingOver()).andReturn(finishedProcessing).anyTimes();
    EasyMock.replay(mockEnv);
    return mockEnv;
  }

  public void testGetClassMocks() throws IOException, CannotCompileException {
    List<Class<?>> classesToMock = new ArrayList<Class<?>>();
    classesToMock.add(TestCase.class);
    List<String> expectedMocks =
        new ArrayList<String>(Arrays.asList(new String[] {
            "genmocks." + TestCase.class.getName() + "DelegateInterface",
            "genmocks." + TestCase.class.getName() + "DelegateSubclass"}));
    Set<GeneratedClassFile> mockedClasses =
        getProcessor().getClassMocks(classesToMock, true);

    assertEquals(2, mockedClasses.size());
    for (GeneratedClassFile clazz : mockedClasses) {
      assertTrue(expectedMocks.contains(clazz.getClassName()));
      expectedMocks.remove(clazz.getClassName());
    }
  }

  public void testWriteMocks() throws IOException, CannotCompileException {
    List<Class<?>> classesToMock = new ArrayList<Class<?>>();
    classesToMock.add(TestCase.class);
    Set<GeneratedClassFile> mockedClassesSet =
        getProcessor().getClassMocks(classesToMock, true);
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

    getProcessor(getMockProcessingEnvironment(getMockFiler(getMockFileObject(outputStream))))
        .writeMocks(mockedClassesSet);

    String output = new String(outputStream.toByteArray());
    for (GeneratedClassFile mockClass : mockedClassesSet) {
      String expected = new String(mockClass.getContents());
      assertTrue(output.contains(expected));
      output = output.replace(expected, "");
    }
    assertEquals(0, output.length());
  }

  public void testProcess() {
    assertFalse(getProcessor().process(null,
        getMockRoundEnvironment(getAnnotatedElementsSet(TestCase.class))));
    assertFalse(getProcessor().process(null,
        getMockRoundEnvironment(getAnnotatedElementsSet(TestCase.class), true)));
  }

  public void testFindClassesToMock() {
    Set<? extends Element> annotatedElements = getAnnotatedElementsSet(Set.class, TestCase.class);
    List<Class<?>> classesList = getProcessor().findClassesToMock(annotatedElements);

    assertEquals(annotatedElements.size(), classesList.size());
    assertTrue(classesList.contains(Set.class));
    assertTrue(classesList.contains(TestCase.class));
  }
}