org.deephacks.tools4j.config.test.MockLookup Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of tools4j-config-tck Show documentation
Show all versions of tools4j-config-tck Show documentation
Functional Tests for Tools4j Config
package org.deephacks.tools4j.config.test;
import java.lang.reflect.Field;
import java.util.Collection;
import org.deephacks.tools4j.config.model.Lookup;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
/**
* MockLookup is responsible for mocking lookups.
*/
public class MockLookup extends Lookup {
private Multimap, Object> instances = ArrayListMultimap.create();
@Override
public T lookup(Class clazz) {
@SuppressWarnings("unchecked")
Collection result = (Collection) instances.get(clazz);
if (result.size() != 0) {
return result.iterator().next();
}
return super.lookup(clazz);
}
@SuppressWarnings("unchecked")
@Override
public Collection lookupAll(Class clazz) {
Collection result = (Collection) instances.get(clazz);
if (result.size() != 0) {
return result;
}
return super.lookupAll(clazz);
}
public static void setMockInstances(Class> clazz, Object... instances) {
overrideDefault();
MockLookup thisMockLookup = (MockLookup) Lookup.get();
thisMockLookup.instances.clear();
for (Object object : instances) {
thisMockLookup.instances.put(clazz, object);
}
}
public static void addMockInstances(Class> clazz, Object... instances) {
overrideDefault();
MockLookup thisMockLookup = (MockLookup) Lookup.get();
for (Object object : instances) {
thisMockLookup.instances.put(clazz, object);
}
}
private static void overrideDefault() throws ExceptionInInitializerError {
try {
System.setProperty(Lookup.class.getName(), MockLookup.class.getName());
if (Lookup.get().getClass() != MockLookup.class) {
// Someone else initialized lookup first. Try to force our way.
Field defaultLookup = Lookup.class.getDeclaredField("LOOKUP");
defaultLookup.setAccessible(true);
defaultLookup.set(null, null);
}
if (!Lookup.get().getClass().equals(MockLookup.class))
throw new RuntimeException("Could not set MockLookup");
} catch (Exception x) {
throw new ExceptionInInitializerError(x);
}
}
public static void resetToDefault() throws ExceptionInInitializerError {
try {
System.setProperty(Lookup.class.getName(), "");
Field defaultLookup = Lookup.class.getDeclaredField("LOOKUP");
defaultLookup.setAccessible(true);
defaultLookup.set(null, null);
if (!Lookup.get().getClass().equals(Lookup.class))
throw new RuntimeException("Could reset to default lookup");
} catch (Exception x) {
throw new ExceptionInInitializerError(x);
}
}
}