Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JUnit: using constructor instead of @Before

I'm using JUnit 4. I can't see the difference between initializing in the constructor or using a dedicated init function annotated by @Before. Does this mean that I don't have to worry about it?

Is there any case when @Before gives more than just initializing in the constructor?

like image 706
vbence Avatar asked May 23 '11 07:05

vbence


People also ask

Can JUnit test class have constructor?

JUnit provides lot of methods to test our cases. We can test the constructor of a class using the same techniques we have used in our previous examples. Sometimes we need to initialize the objects and we do them in a constructor. In JUnit we can also do same using the @Before method.

How do you test a constructor in JUnit?

To test that a constructor does its job (of making the class invariant true), you have to first use the constructor in creating a new object and then test that every field of the object has the correct value. Yes, you need need an assertEquals call for each field.

What does @before mean in JUnit?

In JUnit 5, the tags @BeforeEach and @BeforeAll are the equivalents of @Before and @BeforeClass in JUnit 4. Their names are a bit more indicative of when they run, loosely interpreted: 'before each tests' and 'once before all tests'.

What is the purpose of JUnit @before and @after annotations?

junit Getting started with junit @Before, @After An annotated method with @Before will be executed before every execution of @Test methods. Analogous an @After annotated method gets executed after every @Test method. This can be used to repeatedly set up a Test setting and clean up after every test.


1 Answers

No, using the constructor to initialize your JUnit test fixture is technically equal to using the @Before method (due to the fact that JUnit creates a new instance of the testing class for each @Test). The only (connotational) difference is that it breaks the symmetry between @Before and @After, which may be confusing for some. IMHO it is better to adhere to conventions (which is using @Before).

Note also that prior to JUnit 4 and annotations, there were dedicated setUp() and tearDown() methods - the @Before and @After annotations replace these, but preserve the underlying logic. So using the annotations also makes life easier for someone migrating from JUnit 3 or earlier versions.

Notable differences

More details from comments:

  • @Before allows overriding parent class behavior, constructors force you to call parent class constructors
  • The constructor runs before subclass constructors and @Rule methods, @Before runs after all of those
  • Exceptions during @Before cause @After methods to be called, Exceptions in constructor don't
like image 165
Péter Török Avatar answered Sep 22 '22 23:09

Péter Török