Frage

I have a project in Java with JUnit tests in Scala. Each test class is annotated with @Test:

import org.junit.Test

@Test
class SomeTest {
  ...
}

JUnit API says that @Test is a method annotation. However, when I delete the @Test annotations from the classes while keeping method annotations intact, many tests are not executed when running from Eclipse.

So what is the purpose of @Test annotation applied to a class and why are some of the tests not run when these annotations removed?

War es hilfreich?

Lösung

Scala does not check the ElementType for annotations (even outside of Scala IDE), so there is no 'purpose' for a @Test annotation for a class in Scala.

In fact, you can apply any annotation to a class, Scala does not prevent this. Using the following example:

import org.junit.Test
import org.junit.Rule

@Rule
class Foo {
    @Test
    def test(filename: String) = println("test");
}

after compilation, you get a @Rule annotation on the class. This is a known feature, because AFAIK, you can 'apply' an annotation on a field in the source, but will actually end up on the method, if you use on of the target annotations.

If you're running your tests through any of the standard test runners, the @Test on the class shouldn't make any difference. The only thing that counts is the @Test annotation on the method.

When you're using JUnit in Scala, you should follow the same rules as with Java.

Andere Tipps

The JUnit @Test annotation is a method annotation (see the source here), not a class annotation. So not only is it unnecessary to add @Test to a class, it should not even be allowed.

It is weird that:

  • Eclipse is even allowing you to add it to a Scala class.
  • This is changing the behaviour of the tests.

Sounds like a bug in either Eclipse or, more likely, the Eclipse Scala plugin.

You say that many tests are not executed "when running from Eclipse". Does this mean that you can successfully run all the tests outside of Eclipse?

FYI with TestNG, you can specify @Test at the class level, and this will turn all the public methods of this class into tests. But yes, as far as I know, JUnit doesn't support this.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top