-3

Being new to jUnit what I have done so far is setting up my dependencies (i.e. creating objects) within the test methods itself.

Questions:

  1. Eclipse mocks about unused variables, though. Is this what setUp and tearDown are for?

  2. Is it good practice to create objects within setUp and then null them out via tearDown?

  3. What are other use cases for the methods above?

  4. What is the purpose of working with pre-Suite setUp and tearDown. Can someone give an example when this comes in handy?

Cheers, Andrew

x80486
  • 6,627
  • 5
  • 52
  • 111
Andrew Tobey
  • 915
  • 3
  • 10
  • 27
  • I m not sure, why this question have down votes??, As per me this question stage properly and cover the all aspect of any question should cover. – Simmant Feb 23 '18 at 11:11

1 Answers1

1

Being new to jUnit what I have done so far is setting up my dependencies (i.e. creating objects) within the test methods itself.

If they are initialized and cleaned up correctly there is nothing wrong with this approach. You have to do it this way, if different tests need different dependencies.

Eclipse mocks about unused variables, though. Is this what setUp and tearDown are for?

Unused variables have nothing to do with setUp and tearDown methods. You should either use them or remove them.

Is it good practice to create objects within setUp

In some cases setUp method (or nowadays @Before annotation) is necessary. Usually the constructor and inline initializes will work just as well. @Before annotation is useful, if you have inheritance in your tests or you want to take advantage of @Rules during initialization.

and then null them out via tearDown?

This is a bad idea. tearDown (or nowadays @After annotation) should be used to clean up external resources like connections and files or to revert changes made to static state of your application. There is no need to null fields as garbage collector will reclaim them anyway.

What is the purpose of working with pre-Suite setUp and tearDown. Can someone give an example when this comes in handy?

Sometimes you want to share some resources between tests. For example slow to create database connections. Suite methods let you create them once per suite instead of once per test or per test class.

Piotr Praszmo
  • 17,928
  • 1
  • 57
  • 65