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'
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.