简体   繁体   中英

How do you clear objects between JUnit/Maven tests?

I'm testing different parts of a miniature search engine, and some of the JUnit tests are leaving entries in the index that interfere with other tests. Is there a convention in JUnit/Maven for clearing objects between tests?

There are 2 particular annotations that can help you with this, and are intended to be used in cases such as yours:

@After defines that a certain method must be executed after every @Test , while @AfterClass is the method to execute once the entire test class has been executed. Think of the latter as a last cleanup method to purge any structures or records you've been using and sharing between tests so far.

Here is an example:

@After
public void cleanIndex() {
    index.clear(); //Assuming you have a collection
}

@AfterClass
public void finalCleanup() {
    //Clean both the index and, for example, a database record.
}

Note : They have their counterparts ( @Before and @BeforeClass ) that to exactly the opposite by invoking the related methods before a @Test method and before starting to execute the @Test s defined on that class. This ones are the setUp used in previous versions of JUnit.


If you can't use annotations, the alternative is to use the good old tearDown method:

public void tearDown() {
    index.clear(); //Assuming you have a collection.
}

This is provided by the JUnit framework and behaves like a method annotated with @After .

You should make use of the @Before annotation to guarantee that each test is running from a clean state. Please see: Test Fixtures .

Inside of your junit testing class, you can override the methods setup and teardown . setup will run before every one of your tests while teardown will run after every single junit test that you have.

ex:

public class JunitTest1 {

    private Collection collection;

    //Will initialize the collection for every test you run
    @Before
    public void setUp() {
        collection = new ArrayList();
        System.out.println("@Before - setUp");
    }

    //Will clean up the collection for every test you run
    @After
    public void tearDown() {
        collection.clear();
        System.out.println("@After - tearDown");
    }

    //Your tests go here
}

This is useful for clearing out data inbetween tests, but also allows you to not have to reinitialize your fields inside of every single test.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM