有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java ReflectionTestUtils集合字段,spring值注释返回NPE

我有一个实现接口的类。该类有一个私有双字段field1,它使用@Valuespring注释从应用程序属性中读取值

我正在开发测试,需要从该类填充该字段。为了实现这一点,我正在使用:

        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) 个答案

  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. # 2 楼答案

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

    YourClass object = new YourClass();
    ReflectionTestUtils.setField(object, "field1", value);
    
  3. # 3 楼答案

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

    @InjectMocks
    AbcdImpl abcdImpl;
    

    然后:

    ReflectionTestUtils.setField(abcdImpl, "field", "value");
    
  4. # 4 楼答案

    我无法解释为什么会得到NullPointer,但我在测试中使用以下形式作为类级注释来设置属性:

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