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

improve Whitebox.setInternalState() #99

Merged
merged 3 commits into from
Apr 27, 2022
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,18 @@ public class Whitebox {

public static final char SEPARATOR = '.';

public static void setInternalState(Object target, String fieldName,
Object value) {
public static void setInternalState(Object target,
String fieldName, Object value) {
assert target != null;
assert fieldName != null;
int sep = fieldName.lastIndexOf(SEPARATOR);
if (sep > 0) {
target = getInternalState(target, fieldName.substring(0, sep));
String prefix = fieldName.substring(0, sep);
Object result = getInternalState(target, prefix);
E.checkArgument(result != null,
"Can't set value on null field: `%s.%s`",
target, prefix);
target = result;
fieldName = fieldName.substring(sep + 1);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ public void testSetInternalState() {

Whitebox.setInternalState(test1, "ivalue", 11);
Assert.assertEquals(11, Whitebox.getInternalState(test1, "ivalue"));
Assert.assertEquals(11, test1.ivalue);

Whitebox.setInternalState(test1, "test2.fvalue", 22f);
Assert.assertEquals(22f, Whitebox.getInternalState(test1,
Expand All @@ -97,6 +98,17 @@ public void testSetInternalState() {
});
}

@Test
public void testSetInternalFinalState() {
Test1 test1 = newTest();
Assert.assertEquals(1, test1.ivalueFinal);

Whitebox.setInternalState(test1, "ivalueFinal", 2);
Assert.assertEquals(2, Whitebox.getInternalState(test1, "ivalueFinal"));
// FIXME: seems don't take effect!!!
Assert.assertEquals(1, test1.ivalueFinal);
}

@Test
public void testInvokeStatic() {
Assert.assertEquals(1, Whitebox.invokeStatic(Test1.class, "svalue"));
Expand Down Expand Up @@ -159,7 +171,10 @@ private static Test1 newTest() {
private static class Test1 {

private static int staticValue = 1;

private int ivalue = 1;
private final int ivalueFinal = 1;

private Test2 test2;
private TestSubClass test4;

Expand Down