简体   繁体   中英

ReflectionTestUtils set field with spring value annotation returning NPE

I have a class which implements a interface. That class has a private double field field1 which reads value from application properties using @Value spring annotation.

I'm developing tests and I need to populate that field from that class. To achieve that I'm using:

        ReflectionTestUtils.setField(Class.class, "field1", value, double.class);

I'm getting always null pointer exception, but the debug log shows:

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

Does someone know how can I set value to this field using reflection or just how to populate some value to this class field? I don't have any instance of that class, but interfaces.

the first argument is the instance, not the class

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

It should be an instance of an object that you pass to setField. For instanse assuming Mockito it should go:

@InjectMocks
AbcdImpl abcdImpl;

and then:

ReflectionTestUtils.setField(abcdImpl, "field", "value");

here is my some example test for 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);

    }

I can not say why you get the NullPointer but I use the following form as class level annotation in my tests to set a property:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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