强制将设置器添加到一个类中,以在测试方法中填充数值。

huangapple go评论92阅读模式
英文:

Force setters to a class. To populate values in test methods

问题

我想要为一个没有setter的对象设置值。这只是为了生成一个用于单元测试的对象。这个类位于一个我无法更改的库中。

public class Animal {
    protected String name;
    public Animal() {}
    public String getName() {
        return this.name;
    }
}

假设我需要创建一个Animal对象并设置name,并从中测试不同的情况。

我已经更新了代码。这个片段接近实现。变量是'protected',类是'public'。

英文:

I would like to set value to an object that does not have setters in them. This is purely to generate a an object for unit testing. This class is in a library which I cannot change.

public class Animal {
    protected String name;
    public Animal() {}
    public String getName() {
        return this.name;
    }
}

Lets say I have to create an object for Animal and set name and test different cases from them.

I have updated the code. This is snippet is close to the implementation. The variable is 'protected' and the class is 'public'

答案1

得分: 0

自从字段被声明为 protected,子类可以访问它们。这意味着你可以选择使用 双括号初始化 习语来创建一个本地子类:

Animal animal = new Animal() {{
    name = "foo";
}};

理想情况下,你应该尽量找到一种使用库提供的方法来创建这些对象的方式。你无法确定在测试中创建的对象是否与应用程序在运行时创建的对象相匹配。目标是尽量减少在测试运行和实际运行时系统行为之间的差异。

英文:

Since the fields are protected, subclasses have access to them. This means one option you have is the double-brace initialization idiom, which creates a local subclass:

    Animal animal = new Animal() {{
        name = "foo";
    }};

Ideally, you should try to find a way to create these objects using methods provided by the library. You have no way of knowing if the objects you are creating in the test will match the objects that will be created by the application when it runs. The goal is to minimize the difference between how the system behaves in test runs and how it behaves when running for real.

huangapple
  • 本文由 发表于 2020年8月10日 09:54:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/63333150.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定