簡體   English   中英

如何使用 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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM