JUnit test a public method impact on non-public fields

AllirionX :

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:

  • I can call the duplicate method
  • I cannot check the state of the newly created object against the state of the original object due to the package visibility
  • I would like to avoid creating getters as the state of a B object is not supposed to be visible outside of the package

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

GhostCat salutes Monica C. :

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=142822&siteId=1