【问题标题】:ReflectionTestUtils set field with spring value annotation returning NPEReflectionTestUtils 设置带有返回 NPE 的弹簧值注释的字段
【发布时间】:2020-05-20 11:17:44
【问题描述】:

我有一个实现接口的类。该类有一个私有双字段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].

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

【问题讨论】:

    标签: java spring reflection


    【解决方案1】:

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

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

    【讨论】:

    • 这是关键the first argument is the instance, not the class
    【解决方案2】:

    它应该是您传递给 setField 的对象的实例。 例如假设 Mockito 它应该去:

    @InjectMocks
    AbcdImpl abcdImpl;
    

    然后:

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        【解决方案4】:

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

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

        【讨论】:

        • 但是我有一个类MyTest,在这个过程中使用AnotherClass,它注入了一个私有字段。我还能用你的方式吗?
        • 当然,我的字段也大多是私有的。这不是关于 spring 设置纯私有字段,而是通过 @Value 注释将正确的值传递给该字段。当然你的测试类必须用@RunWith(SpringJUnit4ClassRunner.class)注释
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-03-28
        • 1970-01-01
        • 2013-08-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多