繁体   English   中英

ReflectionTestUtils 设置带有弹簧值注释返回 NPE 的字段

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM