AllirionX
AllirionX

Reputation: 1143

JUnit test a public method impact on non-public fields

In a package are two classes A and B. Each A object has a reference to a B object. The state of a B instance should only be visible by A, meaning all the B attributes have a package visibility. This is due to the A class being too complex - I had split it in two (and it was semantically correct to do so).

The B class has a public method duplicate() performing a kind-of-deep-copy (meaning some attributes are deeply copied recursively, and for some only the reference is copied).

Problem is I need to make test the duplicate method:

Is there a way to make the attributes in B visible for testing only?

Upvotes: 2

Views: 130

Answers (1)

GhostCat
GhostCat

Reputation: 140427

I cannot check the state of the newly created object against the state of the original object due to the package visibility

Then your test setup is simply wrong.

It is the default best practice in Java unit testing that

  • class ProductionA is tested by a class named ProductionATest ... and more importantly that
  • ProductionA and ProductionATest both live in the same package

They should reside in different directories, but exist in the same package!

The typical maven project structure therefore looks like:

project-root / src / main / java / my / com / package

and

project-root / src / test / java / my / com / package

When you follow that practice you have no problems getting to package protected fields and methods (and that is exactly why everybody organizes production and test classes in such ways).

Upvotes: 4

Related Questions