[英]Use of ReflectionTestUtils.setField() in Junit testing
[英]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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.