如何使用 ReflectionTestUtils.setField() 来设置私有字符串数组?
How to use ReflectionTestUtils.setField() to set a private String array?
我有点惊讶 - 在我的 class 中,我有一个 private String[] permissions;
字段,我想在 运行 测试时从外部设置它。我想过使用 ReflectionTestUtils.setField()
但看起来没有办法做到这一点。还有其他方法可以做到这一点吗?不,我不允许为其声明任何设置器:/
这里其实可以用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>
我有点惊讶 - 在我的 class 中,我有一个 private String[] permissions;
字段,我想在 运行 测试时从外部设置它。我想过使用 ReflectionTestUtils.setField()
但看起来没有办法做到这一点。还有其他方法可以做到这一点吗?不,我不允许为其声明任何设置器:/
这里其实可以用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>