File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Testing and the fly likes testing methods with junit Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Engineering » Testing
Bookmark "testing methods with junit" Watch "testing methods with junit" New topic

testing methods with junit

Argoni Mahun

Joined: Jan 29, 2012
Posts: 1
hi, I wrote junit tests for a class which has add and delete method. For add method I instantiated the class call add and then asserted. For delete method I first called add method, then deleted it and asserted. I wonder if it is true to call add method while testing delete method. because add can be wrong and effect the delete method test case. İs there any better practice?

My code is:

public void testAddLMTask() {
LMTask task = new LMTask();
LMTaskCtrl taskCtrl = new LMTaskCtrl();
assertEquals("Task not added", 1, taskCtrl.getTaskList().size());

public void testDeleteTask() {
LMTask task = new LMTask();
LMTaskCtrl taskCtrl = new LMTaskCtrl();
assertEquals("Task not deleted", 0, taskCtrl.getTaskList().size());
Jeanne Boyarsky
author & internet detective

Joined: May 26, 2003
Posts: 33130

I see no problem with calling add. You have another test that shows it is working. If add becomes a blank method, that first test fails.

[OCA 8 book] [Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Other Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, TOGAF part 1 and part 2
Brian Burress
Ranch Hand

Joined: Jun 30, 2003
Posts: 128
I agree with Jeanne's assessment. Specifically, I have seem some approaches where the codeer avoids assertion errors that cascade through the tests (i.e. if one function point fails, you'd want to avoid it causing a bunch of other tests to fail). You could split the code up conceptually into sections using comments like "setup" and "actual test". In the testDeleteTask, the addTask logic would be under setup and as such one would not expect to see asserts in the section.

With that said, there are some tests where I do have asserts to validate state before and after a test. Arguably when I do this I am effectively merging multiple tests into one. When I do this, I am typically writing an integration or acceptance type of test. It appears your test is more of a unit test the approach as you have coded "fits" ok.
I agree. Here's the link:
subject: testing methods with junit
It's not a secret anymore!