gpt4 book ai didi

java - 在方法中设置私有(private)变量和读取值

转载 作者:行者123 更新时间:2023-11-28 20:42:55 24 4
gpt4 key购买 nike

我试图在我的 Spock 测试中在类中设置私有(private)变量并在类方法中读取该值,但它不起作用。

模板类

public class Template {
private String finalMessage;

public String getMessage() {
return finalMessage;
}

模板测试.groovy

    given: "A template"
Template template = Mock()

when: "setting field"
String templ = "<APP/>aaaa";

Field f2 = Template.class.getDeclaredField("finalMessage");
f2.setAccessible(true);

f2.set(template ,templ);

then: "tags set contains all tags"
System.out.println(f2.get(template));
System.out.println(template.getMessage());

输出

<APP/>aaaa
null

我正在模拟这个模板对象,因为它正在连接到数据库,但我不想使用它。

最佳答案

由于 Template 实例是一个 mock 并且您还没有对 getMessage() 方法进行 stub,它返回 null。这是模拟对象的默认行为。实际 getMessage() 方法中的代码永远不会被调用。您必须对方法进行 stub 以返回您希望它们返回的内容。您可能会以调用实际代码的方式对其进行 stub ,但这取决于您使用的模拟框架。

关于java - 在方法中设置私有(private)变量和读取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25119135/

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