gpt4 book ai didi

java - 如何在构造函数中设置@Value的值以进行测试

转载 作者:行者123 更新时间:2023-12-01 18:00:51 25 4
gpt4 key购买 nike

我想将“ignore”值设置为 true 和 false。目前已经能够在 @Before 将其设置为 true。但我怎样才能通过将其设置为 false 来进行测试。请注意,我需要将其作为构造函数初始化。

由于在构造函数中设置了值,因此通过 ReflectionTestUtils 设置值将不起作用。我可以再次调用构造函数并将值设置为 false,但这将涉及此测试类中的大量设置以及所有相关的模拟等等,这会变得困惑。有没有解决的办法?

我有以下构造函数

// many other variables not relevant for this question
private final boolean ignore;

public Client(@Value("${a.error}") boolean ignore) {
// setting many other variables not relevant for this question
this.ignore = ignore;
}

测试时:

@Before
public void setUp() {
client = new Client(true);
//many other setups
}

// tests correctly fine cos I set the ignore to true
@Test
public void testing(){
// someMethod uses the ignore value to do some actions and return true / false
assertTrue(client.someMethod());
}

@Test
public void howToTestIgnoreSetToFalse(){
// ?
}

最佳答案

我可以在这里建议 3 个解决方案:

  1. 使用 Spring 的 ReflectionUtils
@Before
public void setUp() {
client = new Client(true);
// rest of initialization
}

@Test
public void testing(){
assertTrue(client.someMethod());
}

@Test
public void howToTestIgnoreSetToFalse(){
Field fieldIgnore = Client.class.getDeclaredField("ignore");
ReflectionUtils.makeAccessible(fieldIgnore);
ReflectionUtils.setField(fieldIgnore, client, false);

assertFalse(client.someMethod());
}
  • 使用默认的 Reflection API
  • @Test
    public void howToTestIgnoreSetToFalse(){
    Field fieldIgnore = Client.class.getDeclaredField("ignore");
    // only the way of how you're initializing field is changed,
    // everything else is the same
    fieldIgnore.setAccessible(true);
    Field modifiersField = Field.class.getDeclaredField("modifiers");
    modifiersField.setAccessible(true);
    modifiersField.setInt(f, f.getModifiers() & ~Modifier.FINAL);
    fieldIgnore.set(client, false);

    assertFalse(client.someMethod());
    }
  • 将初始化提取到单独的方法
  • // setup method doesn't required anymore

    @Test
    public void testing(){
    Client client = createClient(true);
    assertTrue(client.someMethod());
    }

    @Test
    public void howToTestIgnoreSetToFalse(){
    Client client = createClient(false);
    assertTrue(client.someMethod());
    }

    // factory method to prepare mocked/initialized instance
    private static Client createClient(boolean ignore) {
    Client client = new Client(ignore);
    // do common initialization
    // setup your mocks
    return client;
    }

    希望对你有帮助!

    关于java - 如何在构造函数中设置@Value的值以进行测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60633461/

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