I have some doubt when I should create an object in an Unit Test when the object needs to be stopped cleanly.
Usecase: I have a class ComplexClass which has 3 functions:
- Start(): starts a Thread
- Stop(): stops the thread
- GetX(): which gets a value
When I test this class I want to check if GetX() returns 42, but first I have to start the thread, and after it I want to stop the Thread. (During testing I don't want many dangling threads running).
Are fixtures the way to do this?:
class TestComplexClass(object):
@pytest.fixture()
def complexclass(self, request):
print ("[setup] ComplexClass")
cc = ComplexClass()
def fin():
print ("[teardown] ComplexClass")
cc.stop()
request.addfinalizer(fin)
return cc
def test_GetX(self, complexclass):
// do some stuff
complexclass.start()
assert complexclass.GetX() == 42, "GetX() should return 42"
Or should I create the object in the Unit Test?:
class TestComplexClass(object):
def test_GetX(self, complexclass):
// do some stuff
cc = ComplexClass()
try:
cc.start()
assert cc.GetX() == 42, "GetX() should return 42"
except AssertionError:
cc.stop
raise
(Note I'm using Py.Test)