Is it the smell of code that has a special constructor used only during testing?

Suppose I have a class Foothat is created only by an instance of the class Bar:

public Foo(Bar x) {
    this.a = x.a();
    this.b = x.b();
    ...
}

Now I would like to test Foo, assuming that the instance Barwith the desired state is difficult to create. As an additional limitation, the fields a, b, ...are declared final, therefore the settings for these fields are not available.

Perhaps it would be to create an additional constructor in Foo:

protected Foo(A a, B b, ...) {
    this.a = a;
    this.b = a;
    ...
}

This constructor is used only during testing, which I would declare in a comment for this constructor.

Question: Is it the smell of code?

Another solution I was thinking of was a mockery Bar. I wonder if this is the best practice in this case?

+4
3

Mocking Bar, , . MockBar,

Foo foo = new Foo(new MockBar(a, b));
+9

, , , , , . TestBar, Bar Bar. , , . Bar, .

+4

Hmmmmmm.

  • , / , .
  • , , Bar? , . 20- 30- arg, , ( 20- 30- arg 20- ] 30- "return this")?

, ? - , - , , , . , . " , ", , must execute some code whose purpose is simply to successfully complete the test. These are slightly fewer problems in tests aimed at smaller individual parts of the application. "Testing" is not always the same as "testing." Testing the steering arms for cars means something like checking if it can withstand the torque that it says can affect tin. You do not do the same when testing the whole machine. Testing a part is not the same as testing an entire assembly.

0
source

All Articles