[英]Spring ReflectionTestUtils does not set static final field
[英]ReflectionTestUtils set field with spring value annotation returning NPE
我有一個實現接口的類。 該類有一個私有的雙字段field1
,它使用@Value
spring 注釋從應用程序屬性中讀取值。
我正在開發測試,我需要從該類中填充該字段。 為了實現這一點,我正在使用:
ReflectionTestUtils.setField(Class.class, "field1", value, double.class);
我總是收到空指針異常,但調試日志顯示:
DEBUG org.springframework.test.util.ReflectionTestUtils - Setting field 'field1' of type [double] on target object [null] or target class [class com.abcClass] to value [value]
。
有人知道如何使用反射為該字段設置值,或者如何為該類字段填充一些值? 我沒有該類的任何實例,但有接口。
第一個參數是實例,而不是類
YourClass object = new YourClass();
ReflectionTestUtils.setField(object, "field1", value);
它應該是您傳遞給 setField 的對象的實例。 例如,假設 Mockito 它應該去:
@InjectMocks
AbcdImpl abcdImpl;
進而:
ReflectionTestUtils.setField(abcdImpl, "field", "value");
這是我對 ReflectionTestUtils 的一些示例測試。
@ExtendWith(MockitoExtension.class)
class RedisConfigTest {
@Mock
JedisConnectionFactory jedisConnectionFactory;
@Mock
RedisTemplate redisTemplate;
@InjectMocks
@Spy
private RedisConfig config = new RedisConfig(jedisConnectionFactory, redisTemplate);
@BeforeEach
void setUp() {
ReflectionTestUtils.setField(config, "master", "mymaster");
ReflectionTestUtils.setField(config, "redisSentinels", "localhost:6379");
lenient().when(config.jedisConnectionFactory()).thenReturn(jedisConnectionFactory);
lenient().when(config.redisTemplate()).thenReturn(redisTemplate);
}
@Test
void jedisConnectionFactory(){
Assertions.assertEquals(config.jedisConnectionFactory(), jedisConnectionFactory);
}
我不能說你為什么得到 NullPointer 但我在我的測試中使用以下形式作為類級別注釋來設置屬性:
...
@TestPropertySource(properties = {
"key.from.properties=myValue",
})
public class MyTest {
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.