Junior — Middle
How can you ensure that a fixture is called after the completion of a test or script?
sobes.tech AI
Answer from AI
To ensure a fixture is called after a test or script finishes, mechanisms like teardown or finalizers are usually used, which guarantee the execution of cleanup code regardless of the test result.
In popular testing frameworks, this is implemented through special methods or decorators:
- In pytest, you can use a fixture with the
yieldparameter:
import pytest
@pytest.fixture
def resource():
# setup
res = acquire_resource()
yield res
# teardown
release_resource(res)
- In unittest (Python), the
tearDown()method is called after each test:
import unittest
class MyTest(unittest.TestCase):
def setUp(self):
self.res = acquire_resource()
def tearDown(self):
release_resource(self.res)
def test_something(self):
self.assertTrue(use_resource(self.res))
- In Java with JUnit, the
@Afteror@AfterEachannotation is used:
@After
public void tearDown() {
releaseResource();
}
Thus, the fixture or resource is released in a block that is guaranteed to execute after the test, even if the test fails with an error.