gpt4 book ai didi

java - 如何使用ReflectionTestUtils.setField()设置私有(private)String数组?

转载 作者:行者123 更新时间:2023-12-01 17:27:14 26 4
gpt4 key购买 nike

我在这里有点惊讶 - 在我的类(class)中,我有一个 private String[] Permissions; 字段,我想在运行测试时从外部设置该字段。我想过使用 ReflectionTestUtils.setField() 但看起来没有办法做到这一点。我还有其他方法可以做到这一点吗?不,我不允许为其声明任何 setter :/

最佳答案

这里实际上可以使用ReflectionTestUtils

假设您的类(class)如下所示:

public class Clazz {

private String[] permissions;

public String[] getPermissions() {
return permissions;
}
}

然后,在测试中你可以这样做:

import org.junit.Assert;
import org.junit.Test;
import org.springframework.test.util.ReflectionTestUtils;

@Test
public void test() {
Clazz clazz = new Clazz();

String[] s = new String[2];
s[0] = "asd";
s[1] = "qwe";

ReflectionTestUtils.setField(clazz, "permissions", s);

Assert.assertArrayEquals(new String[]{"asd", "qwe"}, clazz.getPermissions());
}

spring-boot-starter-test 2.2.6.RELEASE ( https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-test/2.2.6.RELEASE ) 相关。

<dependency>
groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>2.2.6.RELEASE</version>
<scope>test</scope>
</dependency>

关于java - 如何使用ReflectionTestUtils.setField()设置私有(private)String数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61195025/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com