Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JUnit test failing because of the method name

Tags:

java

junit

junit4

Why the name of a test method may influence other tests?

I have a suite with 2 classes of tests, and when I change a method name of class1, my test in class2 is ok (green).

I noticed that both classes have a method with the same name, but the test that is failing is neither of these. However if I rename any of them, all tests are ok.

Is it okay to have 2 methods with the same name in different classes, but in the same suite? And the fact that another test fails randomly is just a coincidence?

ps: the order of tests runned is changed after I rename that method. ps2: sorry for my bad English.

That picture can explain better my question: enter image description here

like image 980
patricK Avatar asked Mar 05 '13 19:03

patricK


People also ask

How do I get the method name in JUnit?

As shown above, we can use the getMethodName method of class TestName to display the name of the test.

Why is my JUnit test failing?

When writing unit tests with JUnit, there will likely be situations when tests fail. One possibility is that our code does not meet its test criteria. That means one or more test cases fail due to assertions not being fulfilled.

What does fail () method do in JUnit?

fail() method It can be used to verify that an actual exception is thrown. Usually based on some input when test case expects an exception at a certain line, providing fail() below that line will verify that exception was not thrown as code execution reached fail() method line.

Can we rerun failed test cases in JUnit?

Rerun Failed Tests with JUnit 4 ExampleWe need two classes, one of them is our Rule Class's RetryRule and the other is our Test Class's RetryRuleTest. In RetryRuleTest class, I will open www.swtestacademy.com and get its title and check it with the WRONG expected title.


1 Answers

There is no bug in JUnit! Our team experienced similar results, which are caused by inproper resource management. You can try to rename your failing test so they are executed first. They should turn green now, that's mostly a sign that a resource is accidently shared between tests. In that case you can try to free the resource in the tear down (@After). Here is a little checklist to find the cause:

  • Are there Thread's that survive a test?
  • Are all Executors shutdown and terminated?
  • Are files or streams still open after a test?
  • Are all fields in the Test-class cleared/reinitialised after a test?
  • Avoid using static references or singletons
  • Don't free resource in your test method, only in the tear down method. Otherwise an exception could make this piece of code unreachable.
like image 157
Chriss Avatar answered Sep 25 '22 16:09

Chriss