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

时间:2018-09-26 20:22:18

标签: java spring reflection

我有一个实现接口的类。该类具有一个私有双字段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.a.b.c.Class] to value [value]

有人知道如何使用反射将值设置为该字段,或者如何为该类字段填充一些值吗?我没有该类的任何实例,但有接口。

4 个答案:

答案 0 :(得分:1)

第一个参数是实例,而不是类

YourClass object = new YourClass();
ReflectionTestUtils.setField(object, "field1", value);

答案 1 :(得分:1)

这是我对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);

    }

答案 2 :(得分:0)

我不能说为什么得到NullPointer,但是我在测试中使用以下形式作为类级别的注释来设置属性:

...
@TestPropertySource(properties = {
    "key.from.properties=myValue",
})
public class MyTest {

答案 3 :(得分:0)

它也应该是您也传递setField的对象。 为了暂时假设Mockito,应该去:

@InjectMocks
AbcdImpl abcdImpl;

然后:

ReflectionTestUtils.setField(abcdImpl, "field", "value");
相关问题