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 @Rule
s 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.