add ReflectUtilTest test case (#641) (#679)

pull/684/head
Gdk666 2 years ago committed by GitHub
parent 5f003fb4e0
commit df68a19b16
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -17,6 +17,97 @@
package cn.hippo4j.common.toolkit;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import org.junit.Test;
import java.lang.reflect.Field;
import java.util.Objects;
public class ReflectUtilTest {
@Test
public void getFieldValueTest() {
TestSubClass testSubClass = new TestSubClass();
Object privateField = ReflectUtil.getFieldValue(testSubClass, "privateField");
Assert.isTrue(Objects.equals("privateField", privateField));
Object field = ReflectUtil.getFieldValue(testSubClass, "field");
Assert.isTrue(Objects.equals("field", field));
}
@Test
public void getFieldValueByFiledTest(){
TestSubClass testSubClass = new TestSubClass();
Field privateField = ReflectUtil.getField(TestSubClass.class, "privateField");
Object privateFieldVal = ReflectUtil.getFieldValue(testSubClass, privateField);
Assert.isTrue(Objects.equals("privateField", privateFieldVal));
}
@Test
public void getFieldTest(){
Field privateField = ReflectUtil.getField(TestSubClass.class, "privateField");
Assert.notNull(privateField);
Field field = ReflectUtil.getField(TestSubClass.class, "field");
Assert.notNull(field);
}
@Test
public void getFieldsTest(){
Field[] fields = ReflectUtil.getFields(TestSubClass.class);
Assert.isTrue(Objects.equals(4, fields.length));
}
@Test
public void getFieldsDirectlyTest(){
Field[] fields = ReflectUtil.getFieldsDirectly(TestSubClass.class, false);
Assert.isTrue(Objects.equals(2, fields.length));
fields = ReflectUtil.getFieldsDirectly(TestSubClass.class, true);
Assert.isTrue(Objects.equals(4, fields.length));
}
@Test
public void getFieldNameTest(){
Field privateField = ReflectUtil.getField(TestSubClass.class, "privateField");
String fieldName = ReflectUtil.getFieldName(privateField);
Assert.notNull(fieldName);
Field subField = ReflectUtil.getField(TestSubClass.class, "subField");
String subfieldName = ReflectUtil.getFieldName(subField);
Assert.notNull(subfieldName);
}
@Test
public void setFieldValueTest(){
TestClass testClass = new TestClass();
ReflectUtil.setFieldValue(testClass, "field", "fieldVal");
Assert.isTrue(Objects.equals("fieldVal", testClass.getField()));
Field privateField = ReflectUtil.getField(TestSubClass.class, "privateField");
ReflectUtil.setFieldValue(testClass, privateField, "privateFieldVal");
Assert.isTrue(Objects.equals("privateFieldVal", testClass.getPrivateField()));
}
@Getter
static class TestClass {
private String privateField;
protected String field;
public TestClass() {
this.privateField = "privateField";
this.field = "field";
}
}
class TestSubClass extends TestClass {
private String subField;
}
}

Loading…
Cancel
Save