1

"android.os.SystemProperties" is cannot be used from outside so reflection is used for a set and get operations @see Where is android.os.SystemProperties?

/**
 * Sets the value for the given key.
 * 
 * @throws IllegalArgumentException if the key exceeds 32 characters
 * @throws IllegalArgumentException if the value exceeds 92 characters
 */
private static void setProperty(String key, String val) throws IllegalArgumentException {

    try {
        Class<?> sysProps = Class.forName("android.os.SystemProperties");

        @SuppressWarnings("rawtypes")
        final Class[] argsTypes = { String.class, String.class };
        final Method setter = sysProps.getMethod("set", argsTypes);

        final Object[] params = { key, val };
        setter.invoke(sysProps, params);
    } catch (IllegalArgumentException iaex) {
        System.out.println("IllegalArgumentException :"+ iaex.getMessage());
        throw iaex;
    } catch (Exception ex) {
        System.out.println("Exception :"+ ex.getMessage());
    }
}

/**
 * Get the value for the given key.
 * 
 * @return An empty string if the key is not found
 * @throws IllegalArgumentException if the key length exceeds 32 characters
 */
public static String getProperty(String key) throws IllegalArgumentException {

    String value;
    try {
        Class<?> sysProps = Class.forName("android.os.SystemProperties");

        @SuppressWarnings("rawtypes")
        final Class[] argTypes = { String.class };
        final Method getter = sysProps.getMethod("get", argTypes);

        final Object[] params = { key };
        value = getter.invoke(sysProps, params).toString();

    } catch (IllegalArgumentException iaex) {
        System.out.println("IllegalArgumentException :"+ iaex.getMessage());
        throw iaex;
    } catch (Exception ex) {
        System.out.println("Exception :"+ ex.getMessage());
        value = "";
    }
    return value;
}

my test function from a target application

public class A {
    public static boolean isDone() { return "V1".equals(SystemProperties.get("K1")); }
}

Then I wrote a following test method

@Test
public void Should_return_truth_isDone() {
    try (MockedStatic<A> mocked = mockStatic(A.class)) {
        setProperty("K1", "V1");
        mocked
            .when(() -> A.isDone())
            .thenCallRealMethod();

        System.out.println("     K1:"+ getProperty("K1"));
        System.out.println(" isDone:"+ (A.isDone() ? "O" : "X"));
        assertTrue(A.isDone());
    }
}

Issue is it's always failing and log shows values are empty - which means values are not saved.

Exception :android.os.SystemProperties
K1:
isDone:X

0 Answers0