简体   繁体   中英

How to use ReflectionTestUtils.setField() to set a private String array?

I'm a little surprised here - in my class I have a private String[] permissions; field that I'd like to externally set while running a test. I thought of using ReflectionTestUtils.setField() but it doesn't look like there's a method to do that. Is there any other way I can go about doing this? And no, I'm not allowed to declare any setters for it:/

It's actually possible to use ReflectionTestUtils here.

Assume that your class looks like:

public class Clazz {

    private String[] permissions;

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

Then, in test you can do something like this:

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());
}

Relevant to 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM