Environment { public <T> T getProperty(@NonNull final String key, final T defaultValue) throws RuntimeException { T value = defaultValue; if (!TextUtils.isEmpty(key) && properties != null) { Object property = properties.get(key); if (property == null) { value = defaultValue; } else { Class clazz = defaultValue.getClass(); if(Number.class.isAssignableFrom(clazz)) { Number numberProperty = (Number) property; if(clazz == Integer.class) { value = (T) Integer.valueOf(numberProperty.intValue()); } else if(clazz == Float.class) { value = (T) Float.valueOf(numberProperty.floatValue()); } else if(clazz == Double.class) { value = (T) Double.valueOf(numberProperty.doubleValue()); } else if (clazz == Long.class) { value = (T) Long.valueOf(numberProperty.longValue()); } else if (clazz == Short.class) { value = (T) Short.valueOf(numberProperty.shortValue()); } else if (clazz == Byte.class) { value = (T) Byte.valueOf(numberProperty.byteValue()); } } else if(String.class == clazz || Boolean.class == clazz) { value = (T) property; } else { throw new RuntimeException("Value must be of type Number, String or Boolean"); } } } return value; } Environment(); boolean isProduction(); T getProperty(@NonNull final String key, final T defaultValue); void setProperty(@NonNull final String key, T value); String getName(); void setName(@NonNull final String name); @Override String toString(); @Override boolean equals(final Object object); @Override int hashCode(); static final String ENVIRONMENT_PRODUCTION; }
@Test public void whenKeyDoesntExist_defaultValueReturned() { int value = environment.getProperty("test", 1); assertEquals(value, 1); }
@Test(expected = RuntimeException.class) public void whenValueTypeUnsupported_exceptionIsThrown() { environment.properties.put("test", new Environment()); environment.getProperty("test", new Environment()); }
@Test(expected = RuntimeException.class) public void whenValueTypeDoesntMatchDefaultArgument_exceptionIsThrown() { environment.properties.put("whenValueTypeDoesntMatchDefaultArgument_exceptionIsThrown", 1); boolean result = environment.getProperty("whenValueTypeDoesntMatchDefaultArgument_exceptionIsThrown", false); }
@Test public void whenValidKey_valueIsReturned() { environment.properties.put("test", 1); int value = environment.getProperty("test", 2); assertEquals(value, 1); }