單元測試中使用Spring的ReflectionTestUtils更方便

1 簡介

ReflectionUtilsSpring中一個經常使用的類,屬於spring-core包;ReflectionTestUtils則屬於spring-test包。二者功能有重疊的地方,而ReflectionUtils會更強大。在單元測試時使用ReflectionTestUtils,能增長咱們的便利性。java

假設咱們須要建立一個類,但它的某些成員變量是私有的,而且沒有提供公共的setter方法,而咱們沒法按照它的正常初始化流程來使它的這些成員變量是咱們想要的值。這時就須要想辦法修改一個類的私有變量,而反射能夠幫助到咱們。Spring也提供了反射相關的工具類:ReflectionUtilsReflectionTestUtils,這裏只介紹ReflectionTestUtils的經常使用功能。spring

2 三類主要方法

獲取對象的成員變量:工具

public static Object getField(@Nullable Object targetObject, String name)

給對象注入成員變量:單元測試

public static void setField(Class<?> targetClass, String name, @Nullable Object value)

調用成員方法:測試

public static <T> T invokeMethod(Object target, String name, Object... args)

3 總結

ReflectionTestUtils是一個小工具類,須要用到的時候,天然會感覺到它的益處。code

相關文章
相關標籤/搜索