Search code examples
unit-testingtestingjunitserverassert

Junit testing - Actions for every test. How to minimize code?


I really didn't know how to describe it better in the title, but here it is explained:

I want to write tests for a Rest Api. Meaning: I log into the server for every test, run my call and log out. It would be way less code and more efficient, if I could somehow log into the server at the beginning of the test, do all my calls (still in seperate tests though) and then log out.

Is there a smart way to do this?

Thanks for every reply!


Solution

  • Have you looked at annotation tags? i.e. @Before and @After tags

    So for example:

    @Before
    private void loginToServer() throws Exception {
       /* Some code to do your login 
        and some code to do your repetitive tests
    }
    
    @Test
    private void testEvents() {
    //// Your test code 
    }
    
    @After
    private void logoutServer() throws Exception {
    /// Code to logout of your server
    }
    

    This way your code will always do the Before tag before it runs anything you set in the @Test class. And your @After class will always logout when finished.