views:

511

answers:

2

I have the following code:

    @BeforeClass
    public static void setUpOnce() throws InterruptedException {
        fail("LOL");
    }

And various other methods that are either @Before, @After, @Test or @AfterClass methods.

The test doesn't fail on start up as it seems it should. Can someone help me please?

I have JUnit 4.5

The method is failing in an immediate call to setUp() which is annotated as @before. Class def is :

public class myTests extends TestCase {
+2  A: 

the method must be static and not directly call fail (otherwise the other methods won't be executed).

The following class shows all the standard JUnit 4 method types:

public class Sample {

    @BeforeClass
    public static void beforeClass() {
        System.out.println("@BeforeClass");
    }

    @Before
    public void before() {
        System.out.println("@Before");
    }

    @Test
    public void test() {
        System.out.println("@Test");
    }

    @After
    public void after() {
        System.out.println("@After");
    }

    @AfterClass
    public static void afterClass() {
        System.out.println("@AfterClass");
    }

}

and the ouput is (not surprisingly):

@BeforeClass
@Before
@Test
@After
@AfterClass
Vladimir
You are correct, thanks, but did not start working once i changed to static.
Lynden Shields
Show us the class definition. It might be the case that your class is a subclass of someother, and that parent class may have some method annotated as @BeforeClass, and that method of the parent class is ending up with some errors and causing the halt.
Adeel Ansari
Otherwise, try to add a normal test method.
Adeel Ansari
The method is failing in an immediate call to setUp() which is annotated as @before.Class def is :public class myTests extends TestCase {
Lynden Shields
Are you having any @Test methods?
Adeel Ansari
Yes, as question states.
Lynden Shields
+4  A: 

do NOT extend TestCase AND use annotations at the same time!
If you need to create a test suite with annotations, use the RunWith annotation like:

@RunWith(Suite.class)
@Suite.SuiteClasses({ MyTests.class, OtherTest.class })
public class AllTests {
    // empty
}


public class MyTests {  // no extends here
    @BeforeClass
    public static void setUpOnce() throws InterruptedException {
        ...
    @Test
    ...

(by convention: class names with uppercase letter)

Carlos Heuberger
Yes this is a better option. Didn't know about these @Suite and @RunWith annotations. +1 and thanks for your inputs.
Adeel Ansari
thanks. I had a hard time to find it last week.. kind of just in time
Carlos Heuberger
Thank you Carlos, works fine now. Also thanks for all your help Vinegar.
Lynden Shields