Best Powermock code snippet using org.powermock.core.classloader.MockClassLoaderTest.transform
Source:MockClassLoaderTest.java
...30import org.powermock.core.classloader.annotations.UseClassPathAdjuster;31import org.powermock.core.classloader.javassist.ClassPathAdjuster;32import org.powermock.core.classloader.javassist.JavassistMockClassLoader;33import org.powermock.core.test.MockClassLoaderFactory;34import org.powermock.core.transformers.ClassWrapper;35import org.powermock.core.transformers.MockTransformer;36import org.powermock.core.transformers.MockTransformerChain;37import org.powermock.core.transformers.support.DefaultMockTransformerChain;38import org.powermock.reflect.Whitebox;39@RunWith(Parameterized.class)40public class MockClassLoaderTest {41 private final MockClassLoaderFactory mockClassLoaderFactory;42 private final Class<? extends MockClassLoader> clazz;43 private final MockTransformerChain mockTransformerChain;44 public MockClassLoaderTest(Class<? extends MockClassLoader> clazz, MockTransformer transformer) {45 this.mockClassLoaderFactory = new MockClassLoaderFactory(clazz);46 this.clazz = clazz;47 this.mockTransformerChain = DefaultMockTransformerChain.newBuilder().append(transformer).build();48 }49 @Test50 public void should_load_and_modify_class_from_package_which_specified() throws Exception {51 String className = "powermock.test.support.ClassForMockClassLoaderTestCase";52 MockClassLoader mockClassLoader = mockClassLoaderFactory.getInstance(new String[]{ className });53 mockClassLoader.setMockTransformerChain(mockTransformerChain);54 Class<?> clazz = Class.forName(className, false, mockClassLoader);55 assertClassIsLoaded(clazz, mockClassLoader);56 assertThatInstanceCouldBeCreateAndMethodReturnMockedValue(clazz);57 }58 @Test59 public void should_load_and_not_modify_class_from_package_which_are_not_specified_as_ignored_or_class_to_mock() throws Exception {60 String className = "powermock.test.support.ClassForMockClassLoaderTestCase";61 MockClassLoader mockClassLoader = mockClassLoaderFactory.getInstance(new String[0]);62 mockClassLoader.setMockTransformerChain(mockTransformerChain);63 Class<?> clazz = Class.forName(className, false, mockClassLoader);64 assertClassIsLoaded(clazz, mockClassLoader);65 assertThatInstanceCouldBeCreateAndMethodReturnNotMockedValue(clazz);66 }67 @Test68 public void should_load_system_classes() throws Exception {69 MockClassLoader mockClassLoader = mockClassLoaderFactory.getInstance(new String[]{ "org.mytest.myclass" });70 Class<?> clazz = Class.forName("java.lang.String", false, mockClassLoader);71 assertThat(clazz).as("System class is loaded").isEqualTo(String.class);72 }73 @Test74 public void should_load_defined_class() throws Exception {75 final String className = "my.ABCTestClass";76 final MockClassLoader mockClassLoader = mockClassLoaderFactory.getInstance(new String[]{ className });77 Whitebox.invokeMethod(mockClassLoader, "defineClass", className, MockClassLoaderTest.DynamicClassHolder.classBytes, 0, MockClassLoaderTest.DynamicClassHolder.classBytes.length, this.getClass().getProtectionDomain());78 Class<?> clazz = Class.forName(className, false, mockClassLoader);79 assertThat(clazz).as("Defined class is loaded").isNotNull();80 }81 @Test82 public void should_ignore_pagackage_added_powerMockIgnore_Annotated() throws Exception {83 MockClassLoader mockClassLoader = mockClassLoaderFactory.getInstance(new String[]{ "org.ikk.Jux" });84 MockClassLoaderConfiguration configuration = mockClassLoader.getConfiguration();85 Whitebox.setInternalState(configuration, "deferPackages", new String[]{ "*mytest*" }, MockClassLoaderConfiguration.class);86 Assert.assertFalse(configuration.shouldModify("org.mytest.myclass"));87 }88 @Test89 public void powerMockIgnoreAnnotatedPackagesHavePrecedenceOverPrepareEverythingForTest() throws Exception {90 MockClassLoader mockClassLoader = mockClassLoaderFactory.getInstance(new String[]{ MockClassLoader.MODIFY_ALL_CLASSES });91 MockClassLoaderConfiguration configuration = mockClassLoader.getConfiguration();92 Whitebox.setInternalState(configuration, "deferPackages", new String[]{ "*mytest*" }, MockClassLoaderConfiguration.class);93 Assert.assertFalse(configuration.shouldModify("org.mytest.myclass"));94 }95 @Test96 public void should_find_and_return_a_one_resource_which_exist() throws Exception {97 final MockClassLoader mockClassLoader = mockClassLoaderFactory.getInstance(new String[0]);98 // Force a ClassLoader that can find 'foo/bar/baz/test.txt' into99 // mockClassLoader.deferTo.100 mockClassLoader.deferTo = new ResourcePrefixClassLoader(getClass().getClassLoader(), "org/powermock/core/classloader/");101 // MockClassLoader will only be able to find 'foo/bar/baz/test.txt' if it102 // properly defers the resource lookup to its deferTo ClassLoader.103 URL resource = mockClassLoader.getResource("foo/bar/baz/test.txt");104 assertThat(resource).isNotNull();105 assertThat(resource.getPath()).endsWith("test.txt");106 }107 @Test108 public void should_find_and_return_resources_which_exist() throws Exception {109 final MockClassLoader mockClassLoader = mockClassLoaderFactory.getInstance(new String[0]);110 // Force a ClassLoader that can find 'foo/bar/baz/test.txt' into111 // mockClassLoader.deferTo.112 mockClassLoader.deferTo = new ResourcePrefixClassLoader(getClass().getClassLoader(), "org/powermock/core/classloader/");113 // MockClassLoader will only be able to find 'foo/bar/baz/test.txt' if it114 // properly defers the resources lookup to its deferTo ClassLoader.115 Enumeration<URL> resources = mockClassLoader.getResources("foo/bar/baz/test.txt");116 assertThat(resources.nextElement().getPath()).endsWith("test.txt");117 }118 @Test119 public void resourcesNotDoubled() throws Exception {120 final MockClassLoader mockClassLoader = mockClassLoaderFactory.getInstance(new String[0]);121 // mockClassLoader.setMockTransformerChain(transformerChain);122 // MockClassLoader will only be able to find 'foo/bar/baz/test.txt' if it123 // properly defers the resources lookup to its deferTo ClassLoader.124 Enumeration<URL> resources = mockClassLoader.getResources("org/powermock/core/classloader/foo/bar/baz/test.txt");125 assertThat(resources.nextElement().getPath()).endsWith("test.txt");126 assertThat(resources.hasMoreElements()).isFalse();127 }128 @Test129 public void canFindDynamicClassFromAdjustedClasspath() throws Exception {130 Assume.assumeThat(clazz.getName(), CoreMatchers.equalTo(JavassistMockClassLoader.class.getName()));131 // Construct MockClassLoader with @UseClassPathAdjuster annotation.132 // It activates our MyClassPathAdjuster class which appends our dynamic133 // class to the MockClassLoader's classpool.134 UseClassPathAdjuster useClassPathAdjuster = new MockClassLoaderTest.TestUseClassPathAdjuster();135 final MockClassLoader mockClassLoader = mockClassLoaderFactory.getInstance(new String[0], useClassPathAdjuster);136 // setup custom classloader providing our dynamic class, for MockClassLoader to defer to137 mockClassLoader.deferTo = new ClassLoader(getClass().getClassLoader()) {138 @Override139 public Class<?> loadClass(String name) throws ClassNotFoundException {140 if (name.equals(MockClassLoaderTest.DynamicClassHolder.clazz.getName())) {141 return MockClassLoaderTest.DynamicClassHolder.clazz;142 }143 return super.loadClass(name);144 }145 };146 // verify that MockClassLoader can successfully load the class147 Class<?> dynamicTestClass = Class.forName(MockClassLoaderTest.DynamicClassHolder.clazz.getName(), false, mockClassLoader);148 assertThat(dynamicTestClass).isNotSameAs(MockClassLoaderTest.DynamicClassHolder.clazz);149 }150 @Test151 public void should_autobox_primitive_values() throws Exception {152 String name = (this.getClass().getPackage().getName()) + ".HardToTransform";153 final MockClassLoader mockClassLoader = mockClassLoaderFactory.getInstance(new String[]{ name });154 Class<?> c = mockClassLoader.loadClass(name);155 Object object = c.newInstance();156 Whitebox.invokeMethod(object, "run");157 assertThat(5).isEqualTo(Whitebox.invokeMethod(object, "testInt"));158 assertThat(5L).isEqualTo(Whitebox.invokeMethod(object, "testLong"));159 assertThat(5.0F).isEqualTo(Whitebox.invokeMethod(object, "testFloat"));160 assertThat(5.0).isEqualTo(Whitebox.invokeMethod(object, "testDouble"));161 assertThat(new Short("5")).isEqualTo(Whitebox.invokeMethod(object, "testShort"));162 assertThat(new Byte("5")).isEqualTo(Whitebox.invokeMethod(object, "testByte"));163 assertThat(true).isEqualTo(Whitebox.invokeMethod(object, "testBoolean"));164 assertThat('5').isEqualTo(Whitebox.invokeMethod(object, "testChar"));165 assertThat("5").isEqualTo(Whitebox.invokeMethod(object, "testString"));166 }167 // helper class for canFindDynamicClassFromAdjustedClasspath()168 public static class MyClassPathAdjuster implements ClassPathAdjuster {169 public void adjustClassPath(ClassPool classPool) {170 classPool.appendClassPath(new ByteArrayClassPath(MockClassLoaderTest.DynamicClassHolder.clazz.getName(), MockClassLoaderTest.DynamicClassHolder.classBytes));171 }172 }173 // helper class for canFindDynamicClassFromAdjustedClasspath()174 static class DynamicClassHolder {175 static final byte[] classBytes;176 static final Class<?> clazz;177 static {178 try {179 // construct a new class dynamically180 ClassPool cp = ClassPool.getDefault();181 final CtClass ctClass = cp.makeClass("my.ABCTestClass");182 classBytes = ctClass.toBytecode();183 clazz = ctClass.toClass();184 } catch (Exception e) {185 throw new RuntimeException("Problem constructing custom class", e);186 }187 }188 }189 public static class TestUseClassPathAdjuster implements UseClassPathAdjuster {190 public Class<? extends Annotation> annotationType() {191 return UseClassPathAdjuster.class;192 }193 public Class<? extends ClassPathAdjuster> value() {194 return MockClassLoaderTest.MyClassPathAdjuster.class;195 }196 }197 private static class JavassistMockTransformer implements MockTransformer<CtClass> {198 @Override199 public ClassWrapper<CtClass> transform(final ClassWrapper<CtClass> clazz) throws Exception {200 CtClass ctClass = clazz.unwrap();201 for (CtMethod ctMethod : ctClass.getMethods()) {202 CtClass returnType = ctMethod.getReturnType();203 if (returnType.getName().equals(String.class.getName())) {204 ctMethod.setBody("return null;");205 }206 }207 return clazz;208 }209 }210}...
transform
Using AI Code Generation
1package com.abc;2public class ClassToBeMocked {3 public String getString() {4 return "abc";5 }6}7package com.abc;8import org.junit.Test;9import org.junit.runner.RunWith;10import org.powermock.api.mockito.PowerMockito;11import org.powermock.core.classloader.MockClassLoader;12import org.powermock.core.classloader.annotations.PrepareForTest;13import org.powermock.modules.junit4.PowerMockRunner;14import static org.junit.Assert.assertEquals;15import static org.powermock.api.mockito.PowerMockito.when;16@RunWith(PowerMockRunner.class)17@PrepareForTest({MockClassLoader.class})18public class MockClassLoaderTest {19 public void testMockClassLoader() throws Exception {20 ClassToBeMocked mockedClass = PowerMockito.mock(ClassToBeMocked.class);21 when(mockedClass.getString()).thenReturn("xyz");22 assertEquals("xyz", mockedClass.getString());23 ClassToBeMocked classToBeMocked = (ClassToBeMocked) MockClassLoader.transform("com.abc.ClassToBeMocked");24 assertEquals("xyz", classToBeMocked.getString());25 }26}27 at org.junit.Assert.fail(Assert.java:88)28 at org.junit.Assert.failNotEquals(Assert.java:834)29 at org.junit.Assert.assertEquals(Assert.java:118)30 at org.junit.Assert.assertEquals(Assert.java:144)31 at com.abc.MockClassLoaderTest.testMockClassLoader(MockClassLoaderTest.java:24)32 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)33 at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)34 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)35 at java.lang.reflect.Method.invoke(Method.java:498)36 at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)37 at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)38 at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)39 at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
transform
Using AI Code Generation
1 public void testTransform() throws Exception {2 final MockClassLoader mockClassLoader = new MockClassLoader();3 final Class<?> mockedClass = mockClassLoader.transform(MockClassLoaderTest.class.getClassLoader(), "org.powermock.core.classloader.MockClassLoaderTest$MockedClass");4 final Object instance = mockedClass.newInstance();5 assertThat(instance, notNullValue());6 assertThat(instance, instanceOf(MockedClass.class));7 }8}
transform
Using AI Code Generation
1import org.powermock.core.classloader.MockClassLoaderTest;2import org.powermock.core.classloader.MockClassLoaderTest$MockClass;3public class MockClassLoaderTest$MockClass {4 public static String mock() {5 return "mock";6 }7}8[INFO] --- maven-surefire-plugin:2.19.1:test (default-test) @ powermock-classloading-xstream ---
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!