简体   繁体   English

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

[英]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.该类有一个私有的双字段field1 ,它使用@Value spring 注释从应用程序属性中读取值。

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] . 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.它应该是您传递给 setField 的对象的实例。 For instanse assuming Mockito it should go:例如,假设 Mockito 它应该去:

@InjectMocks
AbcdImpl abcdImpl;

and then:进而:

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

here is my some example test for ReflectionTestUtils.这是我对 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:我不能说你为什么得到 NullPointer 但我在我的测试中使用以下形式作为类级别注释来设置属性:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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