Setup () and teardown () methods in JUnit Testing

Source: Internet
Author: User

The setup and teardown methods have been used for JUnit tests over the past few days. They can be understood simply in this way. Setup mainly implements initialization before the test, teardown mainly achieves garbage collection after testing.

Note that every test method in junit3 will execute them, instead of executing them once in a class, junit4 uses annotations to implement a class only once. Let's take a look at the test below.Code:

Jar:

Http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22junit%22%20AND%20a%3A%22junit%22

 

Junit3.8.1Version:

Import JUnit. framework. testcase; public class junittest extends testcase {@ overrideprotected void setup () throws exception {system. out. println ("set some prerequisites");} @ overrideprotected void teardown () throws exception {system. out. println ("release some resources");} public void testsomething1 () {system. out. println ("execution unit test testsomething1");} public void testsomething2 () {system. out. println ("execution unit test testsomething2 ");}}

Execution result:

Set some prerequisites

Execute unit test testsomething1

Release some resources

Set some prerequisites

Execute unit test testsomething2

Release some resources

 

Junit4.4Version:

Import Org. JUnit. afterclass; import Org. JUnit. beforeclass; import Org. JUnit. test; public class junittest4 {@ beforeclasspublic static void setupbeforeclass () throws exception {system. out. println ("set some prerequisites");} @ afterclasspublic static void teardownafterclass () throws exception {system. out. println ("release some resources") ;}@ testpublic void test1 () {system. out. println ("execution unit test test1") ;}@ testpublic void Test2 () {system. out. println ("execution unit test Test2 ");}}

Execution result:

Set some prerequisites

Execute unit test test1

Execute unit test Test2

Release some resources

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.