JUnit: how to avoid “no runnable methods” in test

2019-01-08 21:04发布

I have switched to JUnit4.4 from JUnit3.8. I run my tests using ant, all my tests run successfully but test utility classes fail with "No runnable methods" error. The pattern I am using is to include all classes with name *Test* under test folder.

I understand that the runner can't find any method annotated with @Test attribute. But they don't contain such annotation because these classes are not tests. Surprisingly when running these tests in eclipse, it doesn't complain about these classes.

In JUnit3.8 it wasn't a problem at all since these utility classes didn't extend TestCase so the runner didn't try to execute them.

I know I can exclude these specific classes in the junit target in ant script. But I don't want to change the build file upon every new utility class I add. I can also rename the classes (but giving good names to classes was always my weakest talent :-) )

Is there any elegant solution for this problem?

10条回答
Bombasti
2楼-- · 2019-01-08 21:40

My specific case has the following scenario. Our tests

public class VenueResourceContainerTest extends BaseTixContainerTest

all extend

BaseTixContainerTest

and JUnit was trying to run BaseTixContainerTest. Poor BaseTixContainerTest was just trying to setup the container, setup the client, order some pizza and relax... man.

As mentioned previously, you can annotate the class with

@Ignore

But that caused JUnit to report that test as skipped (as opposed to completely ignored).

Tests run: 4, Failures: 0, Errors: 0, Skipped: 1

That kind of irritated me.

So I made BaseTixContainerTest abstract, and now JUnit truly ignores it.

Tests run: 3, Failures: 0, Errors: 0, Skipped: 0
查看更多
疯言疯语
3楼-- · 2019-01-08 21:45
  1. If this is your base test class for example AbstractTest and all your tests extends this then define this class as abstract
  2. If it is Util class then better remove *Test from the class rename it is MyTestUtil or Utils etc.
查看更多
Deceive 欺骗
4楼-- · 2019-01-08 21:46

Be careful when using an IDE's code-completion to add the import for @Test.

It has to be import org.junit.Test and not import org.testng.annotations.Test, for example. If you do the latter, you'll get the "no runnable methods" error.

查看更多
祖国的老花朵
5楼-- · 2019-01-08 21:46

In your test class if wrote import org.junit.jupiter.api.Test; delete it and write import org.junit.Test; In this case it worked me as well.

查看更多
在下西门庆
6楼-- · 2019-01-08 21:50

Assuming you're in control of the pattern used to find test classes, I'd suggest changing it to match *Test rather than *Test*. That way TestHelper won't get matched, but FooTest will.

查看更多
The star\"
7楼-- · 2019-01-08 21:50

What about adding an empty test method to these classes?

public void avoidAnnoyingErrorMessageWhenRunningTestsInAnt() {
    assertTrue(true); // do nothing;
}
查看更多
登录 后发表回答