0
我想用pytest(單元測試)獲得更多技巧。如何測試該類__init__方法在pytest中引發異常(Python)
我嘗試測試在沒有必須參數的情況下實例化類時是否引發異常。
我試圖創建一個夾具,但這導致了一個問題,即夾具被調用時,它會嘗試在缺少參數的情況下在其中創建類,並在pytest之前引發異常,實際上斷言異常被引發。
我設法克服這個不使用夾具,只是在測試函數內實例化類,但我不知道是否有一個更優雅的使用夾具的方式。
class MyClass(object):
def __init__(self, must_have_parameter=None):
if not must_have_parameter:
raise ValueError("must_have_parameter must be set.")
當嘗試使用此夾具在測試我自然會得到一個錯誤:
實例類。
@pytest.fixture()
def bad_class_instantiation():
_bad_instance = MyClass()
return _bad_instance
然後有一個測試:
def test_bad_instantiation(bad_class_instantiation):
with pytest.raises(ValueError, message="must_have_parameter must be set."):
bad_class_instantiation()
這個測試的類被測試用例運行之前(也就是我的解釋)實例失敗? 它仍然表明,一個ValueError發生並得到顯示自定義的短信..
如果我改變測試用例:
def test_bad_instantiation():
with pytest.raises(ValueError, message="must_have_parameter must be set."):
bad_instance = MyClass()
,則測試通過。
有沒有使用夾具的方法,或者我應該在測試函數內部調用類並稱它爲一天?
謝謝你的時間。
Tomasz
我只想指出一個「必須擁有」參數應該可能是位置參數,而不是關鍵字參數。 Kwargs幾乎總是可選的(並設置爲合理/理智的默認值)。 – bnaecker
在這種測試中,如果沒有'must_have_parameter'就不能實例化類,我認爲你不需要使用fixture。你最後一個例子_'with pytest.raises(ValueError,message =「must_have_parameter must be set。」):bad_instance = MyClass()'_是正確的方法。 – aneroid