-1

Could someone please advise me on how to test a constructor using junit testing?

I have the below.

public Controller() {
    view = null;
    model = null;
    data = null;
    logger = Logger.getLogger(Controller.class);
    results = Results.getInstance();
}
2787184
  • 3,257
  • 7
  • 37
  • 68
  • I think you need to show us a little more information on exactly what you want to achieve with your test – Raniz Aug 17 '15 at 13:23

2 Answers2

2

Nothing prevents you from calling a constructor in a JUnit test.

If your concern is with the static method calls (like Results.getInstance()), then you need to add to your test architecture something like PowerMock or JMockit.

cahen
  • 11,836
  • 12
  • 39
  • 68
2

Generally the advice would be to construct the object in your test, and then confirm that it acts correctly (getters return the right thing, etc.)

But take a step back: why do you want to test this constructor? It doesn't do anything particularly interesting or tricky (which is a good thing! Constructors usually shouldn't do much). If you construct any instances of this class, the constructor will be implicitly tested.

Usually, for constructors, I'd have a few tests that take bad input (a null arg, for instance) and confirm that the constructor throws an exception - but not much else. In your constructor's case, it doesn't have args but it does rely on the state of Results, so you should put Results into different states and then call the constructor. (Btw, that Results singleton probably isn't a great idea, in part because it makes testing trickier; you should search around for why singletons are bad.)

JUnit's site has a piece of advice that I find helpful: "test until fear [of having bugs in your code] turns to boredom." In the case of a constructor that doesn't access global state (ie, that doesn't use a singleton), that should probably be a pretty low bar.

Community
  • 1
  • 1
yshavit
  • 39,951
  • 7
  • 75
  • 114