我有一个方法:
def cargo_add(self, new_cargo):
assert (new_cargo.weight + self.cargo_weight()) \
<= self.cargocapacity, "Not enough Space left"
我想测试一下它的功能,比如:
def _test_cargo_add():
assert cShip.cargo_add(c1) is AssertionError
所以我可以测试错误处理。但当第一个Assert是错误的程序停止。
3条答案
按热度按时间dgenwo3n1#
如果你的测试框架没有帮助器,或者你没有使用任何帮助器,你可以只使用内置的
try .. except .. else
和isinstance
来做到这一点:或者只显式捕获AssertionError:
pvabu6sv2#
如果使用unittest进行测试,可以使用assertRaises
ih99xse13#
如果你使用pytest,你可以使用raises:
此外,如果您有一个自定义的异常消息,您可以使用以下类型的Assert来检查: