10

I just created a test class from File->New->JUnit Test Cases and this is my whole code:

import static org.junit.jupiter.api.Assertions.*;
import org.junit.After;
import org.junit.Before;
import org.junit.jupiter.api.Test;

class TestingJUnit {

@Before
public void testOpenBrowser() {
    System.out.println("Opening Chrome browser");
}

@Test
public void tesingNavigation() {
    System.out.println("Opening website");
}

@Test
public void testLoginDetails() {
    System.out.println("Enter Login details");
}

@After
public void testClosingBrowser() {
    System.out.println("Closing Google Chrome browser");
}
}

But when I run this cas only @Test annotations are running @Before and @After annotations code are not running. Please guide me I think this is JUnit version or eclipse IDE version problem, and also my all Test classes not running in TestSuit I don't know why although Test Classes are running fine individually. My TestSuit Class is here:

import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;

@RunWith(Suite.class)
@SuiteClasses({TestingJUnit.class, SecondTest.class})
public class TestSuit {

}
Aashir Haque
  • 153
  • 1
  • 2
  • 12

2 Answers2

30

Try using @BeforeEach instead of @Before and @AfterEach instead of @After

Rmahajan
  • 1,311
  • 1
  • 14
  • 23
  • Yes this is working but what about TestSuite?? TestSuit class not executing all classes – Aashir Haque Jan 25 '19 at 13:25
  • Add this `public class FeatureTestSuite { // the class remains empty, // used only as a holder for the above annotations }` check here for more info https://github.com/junit-team/junit4/wiki/Aggregating-tests-in-suites – Rmahajan Jan 25 '19 at 13:33
  • Yes but this is for JUnit 4 and I am working on JUnit 5 – Aashir Haque Jan 25 '19 at 18:17
  • For TestSuit in Junit 5 you need to use `@SelectPackages("packageName")` or `@SelectClasses( TestingJUnit.class )` – Rmahajan Jan 25 '19 at 21:50
0

Try Using This

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

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

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

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

Output will be:

Before
Test 1
After
Before
Test 2
After
Kumar Ajay
  • 222
  • 4
  • 10