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

unit-testing testing junit server assert

44 观看


21 作者的声誉

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!

作者: Lukas W. 的来源 发布者: 2017 年 12 月 27 日

回应 2


149 作者的声誉


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

So for example:

private void loginToServer() throws Exception {
   /* Some code to do your login 
    and some code to do your repetitive tests

private void testEvents() {
//// Your test code 

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.

作者: mvoase 发布者: 2017 年 12 月 27 日


497 作者的声誉

You should use @BeforeClass and @AfterClass.

作者: Eugene 发布者: 2017 年 12 月 27 日