英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论