Search code examples
junit4

Will Junit execute the @Test case when the code in the @before Section fails?


I'm new to Junit. If I execute something in the @before part, and my code fails. e.g. I want to make a server connection, but it fails for some reason.

Will Junit execute my Test in the @Test section even if the @before fails? Because then my test would fail because I haven't a server connection. How can I handle it if its the case?


Solution

  • You can try this out with a basic junit.

    public class SamplePlayTest {
    
        @Before
        public void setup() {
            System.out.println("Before called");
            throw new RuntimeException();
        }
    
        @Test
        public void test() {
            System.out.println("Test case called");
        }
    
    }
    

    This gives output as

    Before called

    And fails with error java.lang.RuntimeException. Test case called is not printed.