Assume I have a class Foo which is only instantiated with an instance of class Bar:
public Foo(Bar x) {
this.a = x.a();
this.b = x.b();
...
}
Now I would like to test Foo, further assuming an instance of Bar with the desired state is difficult to create. As an additional constraint, the fields a, b, ... are declared as final, so setters for this fields are not available.
A possibility would be to create an additional constructor in Foo:
protected Foo(A a, B b, ...) {
this.a = a;
this.b = a;
...
}
This constructor is only used during testing, which I would declare in the comment for this constructor.
Question: Is this a code smell?
Another solution I was thinking of was mocking Bar. Wonder if its the best practice in this case?
Mocking Bar is more likely to be considered best practice. You should be able to create a MockBar so you can do