1 /*
2  * Copyright (C) 2019 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.tools.layoutlib.create;
18 
19 
20 import com.android.tools.layoutlib.create.dataclass.StubClass;
21 
22 import org.junit.Test;
23 
24 import java.io.IOException;
25 
26 import com.google.common.io.ByteStreams;
27 
28 import static org.junit.Assert.assertEquals;
29 import static org.junit.Assert.assertTrue;
30 import static org.junit.Assert.fail;
31 
32 public class StubClassAdapterTest {
33     private static final String STUB_CLASS_NAME = StubClass.class.getName();
34 
35     @Test
testStubbedClass()36     public void testStubbedClass()
37             throws ClassNotFoundException, IOException, IllegalAccessException,
38             InstantiationException {
39         // Always rename the class to avoid conflict with the original class.
40         byte[] classContent = ByteStreams.toByteArray(ClassLoader.getSystemResourceAsStream(
41                 STUB_CLASS_NAME.replace('.', '/') + ".class"));
42 
43         String newClassName = STUB_CLASS_NAME + '_';
44         classContent =
45                 StubClassAdapter.stubClass(new Log(), classContent, newClassName.replace('.', '/'));
46         TestClassLoader myClassLoader = new TestClassLoader(newClassName, classContent);
47         Class<?> aClass = myClassLoader.loadClass(newClassName);
48         assertTrue("StubClass not loaded by the classloader. Likely a bug in the test.",
49                 myClassLoader.wasClassLoaded(newClassName));
50         try {
51             aClass.newInstance();
52             fail("Method should throw a RuntimeException");
53         } catch (RuntimeException e) {
54             assertEquals("Stub!", e.getMessage());
55         }
56     }
57 }
58