Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ReflectionTestUtils: Methods for changing values of attributes #256

Closed
alpkaanaksu opened this issue Dec 2, 2022 · 0 comments
Closed

ReflectionTestUtils: Methods for changing values of attributes #256

alpkaanaksu opened this issue Dec 2, 2022 · 0 comments
Assignees
Labels
enhancement New feature or request

Comments

@alpkaanaksu
Copy link

Is your feature request related to a problem? Please describe.
Sometimes I want to change the values of private attributes while testing student code. There is no ReflectionTestUtils method to do that.

Describe the solution you'd like
A new method (e.g. setValueForNonPublicAttribute, setValueForAttribute...) in the ReflectionTestUtils, which can also find and change an attribute even if it is defined in one of the superclasses.

Describe alternatives you've considered
I created a method myself.

public static void setValueForNonPublicAttribute(Object objectToModify, String attributeName, Object attributeValueToSet) {
        Class cls = objectToModify.getClass();
        do {
            try {
                Field field = cls.getDeclaredField(attributeName);
                field.trySetAccessible();
                field.set(objectToModify, attributeValueToSet);
                return;
            } catch (NoSuchFieldException e) {
                cls = cls.getSuperclass();
            } catch (Exception e) {
                fail("In " + objectToModify.getClass().getSimpleName() + ", " + attributeName + " can not be set to " + attributeValueToSet + ".");
            }
        } while (cls != null);
        fail("Could not find the attribute " + attributeName + " in class " + objectToModify.getClass().getSimpleName() + "! Make sure it exists and check for typos.");
    }

Ares-Version you are using
1.11.0

@MaisiKoleni MaisiKoleni added this to the Version 1.11.1 milestone Dec 11, 2022
@MaisiKoleni MaisiKoleni self-assigned this Dec 11, 2022
@MaisiKoleni MaisiKoleni added the enhancement New feature or request label Dec 11, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants